Skip to content

Commit 88c7a03

Browse files
authored
Create 0019_Remove_nth_node_from_end_of_list.py
vJechsmayr#11 Close the issue- tested on leetCode
1 parent 5d96084 commit 88c7a03

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
7+
class Solution:
8+
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
9+
10+
# use dummy head will make the removal of head node easier
11+
dummy_head = ListNode(-1)
12+
dummy_head.next = head
13+
14+
# cur keeps iteration till the end
15+
# prev_of_removal traverses to the previous node of the one of being removed
16+
cur, prev_of_removal = dummy_head, dummy_head
17+
18+
19+
while cur.next != None:
20+
21+
# n-step delay for prev_of_removal
22+
if n <= 0:
23+
prev_of_removal = prev_of_removal.next
24+
25+
cur = cur.next
26+
27+
n -=1
28+
29+
30+
# Remove the N-th node from end of list
31+
n_th_node = prev_of_removal.next
32+
prev_of_removal.next = n_th_node.next
33+
34+
del n_th_node
35+
36+
return dummy_head.next

0 commit comments

Comments
 (0)