Skip to content

Commit b24d2ef

Browse files
committed
Remove_nth_node_from_end_of_list
1 parent f6ee33e commit b24d2ef

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
class Solution:
8+
# @return a ListNode
9+
def removeNthFromEnd(self, head, n):
10+
if head is None:
11+
return None
12+
elif n == 0:
13+
return head
14+
else:
15+
q = p = pp = head # `pp` is the node preceding `p`
16+
while q is not None:
17+
if n <= 0:
18+
pp = p
19+
p = p.next
20+
q = q.next
21+
n -= 1
22+
# Remove the head node
23+
if pp is p:
24+
head = pp.next
25+
else:
26+
pp.next = p.next
27+
# Free p
28+
return head

0 commit comments

Comments
 (0)