-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19_remove_nth_node_from_end_of_list
65 lines (52 loc) · 1.48 KB
/
19_remove_nth_node_from_end_of_list
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
60
61
62
63
64
65
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
curr = head
lenA = 0
while curr:
lenA += 1
curr = curr.next
if lenA == 1: return []
if lenA == n:
head = head.next
return head
curr = head
for i in range(lenA - n - 1):
curr = curr.next
if n == 1:
curr.next = None
else:
curr.next = curr.next.next
return head
# 2 pointers
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
first = second = dummy
for i in range(n):
first = first.next
while first.next != None:
first = first.next
second = second.next
second.next = second.next.next
return dummy.next