python delete a node at the given position in the linked list

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

showing results for - "python delete a node at the given position in the linked list"
Isabel
21 Apr 2017
1def pop_at(self, position):     
2  
3  #1. check if the position is > 0
4  if(position < 1):
5    print("\nposition should be >= 1.")
6  elif (position == 1 and self.head != None):
7    
8    #2. if the position is 1 and head is not null, make
9    #   head next as head and delete previous head 
10    nodeToDelete = self.head
11    self.head = self.head.next
12    nodeToDelete = None
13  else:    
14    
15    #3. Else, make a temp node and traverse to the 
16    #   node previous to the position
17    temp = self.head
18    for i in range(1, position-1):
19      if(temp != None):
20        temp = temp.next   
21    
22    #4. If the previous node and next of the previous  
23    #   is not null, adjust links 
24    if(temp != None and temp.next != None):
25      nodeToDelete = temp.next
26      temp.next = temp.next.next
27      nodeToDelete = None 
28    else:
29      
30      #5. Else the given node will be empty.
31      print("\nThe node is already null.")