Answers for "Python - Delete a node at the given position in the Linked List"

0

Python - Delete a node at the given position in the Linked List

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.")
Posted by: Guest on July-17-2021

Code answers related to "Python - Delete a node at the given position in the Linked List"

Python Answers by Framework

Browse Popular Code Answers by Language