Python Data Structures - Doubly Linked List Other Related Topics

Python - Delete the first node of the Doubly Linked List



In this method, the first node of the doubly linked list is deleted. For example - if the given list is 10->20->30->40 and the first node is deleted, the list becomes 20->30->40.

Deleting the first node of the Doubly Linked List is very easy. If the head is not null then create a temp node pointing to head and move head to the next of head. Then delete the temp node. If the new head is not null, make the prev of it as null.

Doubly Linked List - Delete First Node

The function pop_front is created for this purpose. It is a 4-step process.

def pop_front(self):
  if(self.head != None):
    
    #1. if head is not null, create a
    #   temp node pointing to head
    temp = self.head
    
    #2. move head to next of head
    self.head = self.head.next 
    
    #3. delete temp node
    temp = None 

    #4. If the new head is not null, then
    #   make prev of the new head as null
    if(self.head != None):
      self.head.prev = None

The below is a complete program that uses above discussed concept of deleting the first node of the doubly linked list.

# node structure
class Node:
  def __init__(self, data):
    self.data = data
    self.next = None
    self.prev = None

#class LinkedList
class LinkedList:
  def __init__(self):
    self.head = None

  #Add new element at the end of the list
  def push_back(self, newElement):
    newNode = Node(newElement)
    if(self.head == None):
      self.head = newNode
      return
    else:
      temp = self.head
      while(temp.next != None):
        temp = temp.next
      temp.next = newNode
      newNode.prev = temp

  #Delete first node of the list
  def pop_front(self):
    if(self.head != None):
      temp = self.head
      self.head = self.head.next 
      temp = None 
      if(self.head != None):
        self.head.prev = None 

  #display the content of the list
  def PrintList(self):
    temp = self.head
    if(temp != None):
      print("The list contains:", end=" ")
      while (temp != None):
        print(temp.data, end=" ")
        temp = temp.next
      print()
    else:
      print("The list is empty.")

# test the code                  
MyList = LinkedList()

#Add four elements in the list.
MyList.push_back(10)
MyList.push_back(20)
MyList.push_back(30)
MyList.push_back(40)
MyList.PrintList()

#Delete the first node
MyList.pop_front()
MyList.PrintList()  

The above code will give the following output:

The list contains: 10 20 30 40
The list contains: 20 30 40