Skip to content

Instantly share code, notes, and snippets.

@Mo-Shakib
Created July 17, 2021 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mo-Shakib/19eb5f6cf7dc75bfc08d7a546be92263 to your computer and use it in GitHub Desktop.
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
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