-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremoveNthFromEnd.py
59 lines (50 loc) · 1.67 KB
/
removeNthFromEnd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
current = head
newList = []
while current:
newList.append(current.val)
current = current.next
print(newList)
newList.pop(-n)
print(newList)
if len(newList) == 0:
return ListNode('')
newHead = ListNode(newList[0])
head2 = newHead
if len(newList) == 0:
return ListNode()
for i in range(len(newList)):
newHead.val = newList[i]
if i < len(newList) - 1:
newHead.next = ListNode()
newHead = newHead.next
return head2
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
first, second, prev = head, head, head
count = 0
while first.next != None:
if count != n - 1 and first.next != None:
first = first.next
count += 1
continue
if first.next != None:
prev = second
first = first.next
second = second.next
if (first.next == None):
prev.next = prev.next.next
return head
if count + 1 == n:
return head.next