Created
July 17, 2021 23:14
-
-
Save Mo-Shakib/b64b71ccb033409c402b9e7a19d1aeba to your computer and use it in GitHub Desktop.
Python - Delete a node at the given position in the Linked List
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
def pop_at(self, position): | |
#1. check if the position is > 0 | |
if(position < 1): | |
print("\nposition should be >= 1.") | |
elif (position == 1 and self.head != None): | |
#2. if the position is 1 and head is not null, make | |
# head next as head and delete previous head | |
nodeToDelete = self.head | |
self.head = self.head.next | |
nodeToDelete = None | |
else: | |
#3. Else, make a temp node and traverse to the | |
# node previous to the position | |
temp = self.head | |
for i in range(1, position-1): | |
if(temp != None): | |
temp = temp.next | |
#4. If the previous node and next of the previous | |
# is not null, adjust links | |
if(temp != None and temp.next != None): | |
nodeToDelete = temp.next | |
temp.next = temp.next.next | |
nodeToDelete = None | |
else: | |
#5. Else the given node will be empty. | |
print("\nThe node is already null.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment