-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveNthFromEnd.py
More file actions
43 lines (39 loc) · 850 Bytes
/
removeNthFromEnd.py
File metadata and controls
43 lines (39 loc) · 850 Bytes
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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# @return a ListNode
def removeNthFromEnd(head, n):
ahead = behind = head
while n > 0:
ahead = ahead.next
n -= 1
if ahead == None:
node = head
head = head.next
node.next = None
return head;
while ahead.next != None:
ahead = ahead.next
behind = behind.next
node = behind.next
behind.next = node.next
node.next = None
return head
a = ListNode('a')
b = ListNode('b')
c = ListNode('c')
d = ListNode('d')
e = ListNode('e')
a.next = b
b.next = c
c.next = d
d.next = e
removeNthFromEnd(a, 2)
assert c.next == e
assert removeNthFromEnd(e, 1) == None
f = ListNode('f')
g = ListNode('g')
f.next = g
assert removeNthFromEnd(f, 2) == g