Skip to content

Commit 7feeb3a

Browse files
committed
Remove Kth Node From End of List
1 parent bce8fde commit 7feeb3a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Amazon/Problem#398.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
Given a linked list and an integer k, remove the k-th node from the end of the list and return the head of the list.
3+
k is guaranteed to be smaller than the length of the list.
4+
Do this in one pass.
5+
"""
6+
def removeNthFromEnd(head, k):
7+
fast = head
8+
for i in range(k):
9+
fast = fast.next
10+
11+
if not fast:
12+
return head.next
13+
14+
slow = head
15+
while fast and fast.next:
16+
fast = fast.next
17+
slow = slow.next
18+
19+
slow.next = slow.next.next
20+
21+
return head

0 commit comments

Comments
 (0)