Skip to content

Added Remove nth Node from the End problem solution in Linked List #11781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@
* [Merge Two Lists](data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](data_structures/linked_list/print_reverse.py)
* [Remove nth Node from the End](data_structures/linked_list/remove_nth_node_from_end.py)
* [Reverse K Group](data_structures/linked_list/reverse_k_group.py)
* [Rotate To The Right](data_structures/linked_list/rotate_to_the_right.py)
* [Singly Linked List](data_structures/linked_list/singly_linked_list.py)
Expand Down
58 changes: 58 additions & 0 deletions data_structures/linked_list/remove_nth_node_from_end.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
class Node:
def __init__(self, val):
self.val = val
self.next = None # Specify that next can be a Node or None


def remove(head: Node, n: int) -> Node:
if head is None:
return None # If the head is None, return None

# Create a dummy node that points to the head
extra = Node(0)
extra.next = head
fast = extra # Make sure fast can be None
slow = extra # Make sure slow can be None

# Move fast ahead by n nodes
for _ in range(n):
if fast is not None:
fast = fast.next

# Move until fast reaches the end
while fast is not None and fast.next is not None:
fast = fast.next
slow = slow.next

# Remove the nth node from the end
if slow is not None and slow.next is not None:
slow.next = slow.next.next # Link slow to the next of the node to be deleted

return extra.next # Return the new head, which may be None if the list is empty


def print_list(head: Node) -> None:
curr = head
while curr is not None:
print(curr.val, end=" ")
curr = curr.next
print() # for a new line


# Creating the linked list 1 -> 2 -> 3 -> 4 -> 5
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 the original list
print("Original list:")
print_list(head)

# Remove the 5th node from the end (the head in this case)
head = remove(head, 5)

# Print the modified list
print("List after removing the 5th node from the end:")
print_list(head)