-
-
Notifications
You must be signed in to change notification settings - Fork 51.1k
Remove nth node from end of list #9880
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
Open
aryandgandhi
wants to merge
14
commits into
TheAlgorithms:master
Choose a base branch
from
aryandgandhi:remove_nth_node_from_end_of_list
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
00b94bb
removed nth node
aryandgandhi c39cf50
Merge branch 'master' of https://github.com/TheAlgorithms/Python into…
aryandgandhi 0993fb4
added link to learn about algo
aryandgandhi b1b6271
Merge branch 'master' of https://github.com/TheAlgorithms/Python into…
aryandgandhi 2214c0d
Addressed PR feedback
aryandgandhi 3bfe23a
Merge branch 'TheAlgorithms:master' into remove_nth_node_from_end_of_…
aryandgandhi d8ec9d4
update bot comments
aryandgandhi 1ed3e7f
Merge branch 'master' of https://github.com/TheAlgorithms/Python into…
aryandgandhi 892f7c5
update type
aryandgandhi 15b8a14
Merge branch 'master' of https://github.com/TheAlgorithms/Python into…
aryandgandhi 64a9452
new branch
aryandgandhi 9e31192
new branch
aryandgandhi 2fe0897
latest updates with typing
aryandgandhi e13fefc
latest updates with typing
aryandgandhi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
143 changes: 143 additions & 0 deletions
143
data_structures/linked_list/remove_nth_node_from_end_of_list.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| """Learn more about this algorithm: https://www.geeksforgeeks.org/delete-nth-node-from-the-end-of-the-given-linked-list/""" | ||
|
|
||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class Node: | ||
| def __init__(self, data: int) -> None: | ||
| self.data = data | ||
| self.next: Node | None = None | ||
|
|
||
|
|
||
| class LinkedListExceptionError(Exception): | ||
| pass | ||
|
|
||
|
|
||
| class LinkedList: | ||
| def __init__(self) -> None: | ||
| self.head: Node | None = None | ||
|
|
||
| # pulled from middle_element_of_linked_list | ||
| def append(self, new_data: int) -> int: | ||
| """ | ||
| >>> link = LinkedList() | ||
| >>> link.append(5) | ||
| 5 | ||
| >>> link.append(6) | ||
| 6 | ||
| """ | ||
| new_node = Node(new_data) | ||
| new_node.next = self.head | ||
| self.head = new_node | ||
| if not self.head: | ||
| raise LinkedListExceptionError( | ||
| "Unexpected error: Head of linked list is None after append operation." | ||
| ) | ||
| return self.head.data | ||
|
|
||
| def view(self) -> str: | ||
|
cclauss marked this conversation as resolved.
|
||
| """ | ||
| >>> link = LinkedList() | ||
| >>> link.append(5) | ||
| 5 | ||
| >>> link.append(6) | ||
| 6 | ||
| >>> link.view() | ||
| '6->5' | ||
| """ | ||
| ret = "" | ||
| temp = self.head | ||
| while temp is not None: | ||
| ret += str(temp.data) | ||
| ret += "->" | ||
| temp = temp.next | ||
| return ret[:-2] | ||
|
|
||
| def remove_nth_from_end(self, position_from_end: int) -> Node | None: | ||
| """ | ||
| >>> link = LinkedList() | ||
| >>> link.remove_nth_from_end(3) | ||
| Traceback (most recent call last): | ||
| ... | ||
| IndexError: No element found. | ||
| >>> link.append(5) | ||
| 5 | ||
| >>> link.append(6) | ||
| 6 | ||
| >>> link.append(8) | ||
| 8 | ||
| >>> link.append(8) | ||
| 8 | ||
| >>> link.append(10) | ||
| 10 | ||
| >>> link.append(12) | ||
| 12 | ||
| >>> link.append(17) | ||
| 17 | ||
| >>> link.remove_nth_from_end(100) | ||
| Traceback (most recent call last): | ||
| ... | ||
| IndexError: Index out of bounds error. | ||
| >>> link.append(-25) | ||
| -25 | ||
| >>> link.append(-20) | ||
| -20 | ||
| >>> link.remove_nth_from_end(3) | ||
| Node() | ||
| >>> | ||
| """ | ||
| # want to have two pointers, one at the start and the other k nodes forward | ||
| # We could complete this in one pass if we stored a self.size variable | ||
| if not self.head: | ||
| raise IndexError("No element found.") | ||
|
|
||
| size = 0 | ||
| current: Node | None = self.head | ||
| while current: | ||
| size += 1 | ||
| current = current.next | ||
|
|
||
| if position_from_end > size or position_from_end <= 0: | ||
| raise IndexError("Index out of bounds error.") | ||
| return None | ||
|
|
||
| first: Node | None = self.head | ||
| for _i in range(position_from_end): | ||
| if first: | ||
| first = first.next | ||
|
|
||
| # This condition checks if position_from_end is equal to the size of the list. | ||
| # If it is, then we simply delete the head node of the list. | ||
| if not first: | ||
| self.head = self.head.next if self.head else None | ||
| return self.head | ||
|
|
||
| second: Node | None = self.head | ||
| prev: Node | None = None | ||
|
|
||
| while first: | ||
| first = first.next | ||
| prev = second | ||
| if second: | ||
| second = second.next | ||
|
|
||
| if prev and second: | ||
| prev.next = second.next | ||
|
|
||
| return self.head | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| link = LinkedList() | ||
| for _ in range(int(input().strip())): | ||
| data = int(input().strip()) | ||
| link.append(data) | ||
| print("Before list: ") | ||
| print(link.view()) | ||
| print(link.remove_nth_from_end(int(input().strip()))) | ||
| print("After list: ") | ||
| print(link.view()) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.