python insert a new node at a given position in the linked list

Solutions on MaxInterview for python insert a new node at a given position in the linked list by the best coders in the world

showing results for - "python insert a new node at a given position in the linked list"
Guillermo
07 Oct 2018
1def push_at(self, newElement, position):     
2  
3  #1. allocate node to new element
4  newNode = Node(newElement)
5
6  #2. check if the position is > 0 
7  if(position < 1):
8    print("\nposition should be >= 1.")
9  elif (position == 1):
10    
11    #3. if the position is 1, make next of the
12    #   new node as head and new node as head
13    newNode.next = self.head
14    self.head = newNode
15  else:    
16    
17    #4. Else, make a temp node and traverse to the 
18    #   node previous to the position
19    temp = self.head
20    for i in range(1, position-1):
21      if(temp != None):
22        temp = temp.next   
23    
24    #5. If the previous node is not null, make 
25    #   newNode next as temp next and temp next 
26    #   as newNode.
27    if(temp != None):
28      newNode.next = temp.next
29      temp.next = newNode  
30    else:
31      
32      #6. When the previous node is null
33      print("\nThe previous node is null.")