Skip to content

Commit 95d06d9

Browse files
committed
added remove_nth_node_from_end.py in linked list Data Structure
1 parent 9a572de commit 95d06d9

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Node():
2+
3+
def __init__(self, val):
4+
self.val = val
5+
self.next = None
6+
7+
8+
def remove(head, n):
9+
extra = Node(0)
10+
extra.next = head
11+
fast = extra
12+
slow = extra
13+
for _ in range(n):
14+
fast = fast.next
15+
16+
while fast.next:
17+
fast = fast.next
18+
slow = slow.next
19+
20+
slow.next = slow.next.next
21+
22+
return extra.next
23+
24+
def print_list(head):
25+
curr = head
26+
while curr:
27+
print(curr.val, end=" ")
28+
curr = curr.next
29+
30+
head = Node(1)
31+
head.next = Node(2)
32+
head.next.next = Node(3)
33+
head.next.next.next = Node(4)
34+
head.next.next.next.next = Node(5)
35+
print_list(head)
36+
head = remove(head, 5)
37+
print_list(head)

0 commit comments

Comments
 (0)