Skip to content

Commit 7b71cd2

Browse files
committed
Remove Nth Node from List End
1 parent d014a9a commit 7b71cd2

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Link: https://www.interviewbit.com/problems/remove-nth-node-from-list-end/
3+
4+
Given a linked list, remove the nth node from the end of list and return its head.
5+
6+
For example,
7+
Given linked list: 1->2->3->4->5, and n = 2.
8+
After removing the second node from the end, the linked list becomes 1->2->3->5.
9+
10+
Note:
11+
If n is greater than the size of the list, remove the first node of the list.
12+
Try doing it using constant additional space.
13+
"""
14+
# Definition for singly-linked list.
15+
# class ListNode:
16+
# def __init__(self, x):
17+
# self.val = x
18+
# self.next = None
19+
20+
class Solution:
21+
# @param A : head node of linked list
22+
# @param B : integer
23+
# @return the head node in the linked list
24+
def removeNthFromEnd(self, A, B):
25+
fast = A
26+
for _ in range(B):
27+
if fast:
28+
fast = fast.next
29+
else:
30+
break
31+
if not fast or not fast.next:
32+
return A.next
33+
34+
slow = A
35+
while fast and fast.next:
36+
fast = fast.next
37+
slow = slow.next
38+
slow.next = slow.next.next
39+
return A

0 commit comments

Comments
 (0)