From 95d06d95f4243287e897a8bfad57773a03cbd0d6 Mon Sep 17 00:00:00 2001 From: sshsrijanr Date: Sat, 5 Oct 2024 20:13:43 +0530 Subject: [PATCH 1/2] added remove_nth_node_from_end.py in linked list Data Structure --- .../linked_list/remove_nth_node_from_end.py | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 data_structures/linked_list/remove_nth_node_from_end.py diff --git a/data_structures/linked_list/remove_nth_node_from_end.py b/data_structures/linked_list/remove_nth_node_from_end.py new file mode 100644 index 000000000000..c6698378e72e --- /dev/null +++ b/data_structures/linked_list/remove_nth_node_from_end.py @@ -0,0 +1,37 @@ +class Node(): + + def __init__(self, val): + self.val = val + self.next = None + + +def remove(head, n): + extra = Node(0) + extra.next = head + fast = extra + slow = extra + for _ in range(n): + fast = fast.next + + while fast.next: + fast = fast.next + slow = slow.next + + slow.next = slow.next.next + + return extra.next + +def print_list(head): + curr = head + while curr: + print(curr.val, end=" ") + curr = curr.next + +head = Node(1) +head.next = Node(2) +head.next.next = Node(3) +head.next.next.next = Node(4) +head.next.next.next.next = Node(5) +print_list(head) +head = remove(head, 5) +print_list(head) From fadbe730fd228a32540ea33378f96e9cf7c3b5b6 Mon Sep 17 00:00:00 2001 From: sshsrijanr Date: Sat, 5 Oct 2024 20:22:08 +0530 Subject: [PATCH 2/2] refactoring --- data_structures/linked_list/remove_nth_node_from_end.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/data_structures/linked_list/remove_nth_node_from_end.py b/data_structures/linked_list/remove_nth_node_from_end.py index c6698378e72e..e261a66568c6 100644 --- a/data_structures/linked_list/remove_nth_node_from_end.py +++ b/data_structures/linked_list/remove_nth_node_from_end.py @@ -1,5 +1,4 @@ -class Node(): - +class Node: def __init__(self, val): self.val = val self.next = None @@ -21,12 +20,14 @@ def remove(head, n): return extra.next + def print_list(head): curr = head while curr: print(curr.val, end=" ") curr = curr.next + head = Node(1) head.next = Node(2) head.next.next = Node(3)