Created
July 17, 2021 22:39
-
-
Save Mo-Shakib/19eb5f6cf7dc75bfc08d7a546be92263 to your computer and use it in GitHub Desktop.
Python - Insert a new node at a 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 insert_at(self, newElement, position): | |
#1. allocate node to new element | |
newNode = Node(newElement) | |
#2. check if the position is > 0 | |
if(position < 1): | |
print("\nposition should be >= 1.") | |
elif (position == 1): | |
#3. if the position is 1, make next of the | |
# new node as head and new node as head | |
newNode.next = self.head | |
self.head = newNode | |
else: | |
#4. 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 | |
#5. If the previous node is not null, make | |
# newNode next as temp next and temp next | |
# as newNode. | |
if(temp != None): | |
newNode.next = temp.next | |
temp.next = newNode | |
else: | |
#6. When the previous node is null | |
print("\nThe previous node is null.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment