Python Data Structures - Linked List Other Related Topics

Python - Delete the first node of the Linked List



In this method, the first node of the 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 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.

Linked List - Delete First Node

The function pop_front is created for this purpose. It is a 3-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 

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

# node structure
class Node:
  def __init__(self, data):
    self.data = data
    self.next = 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

  #Delete first node of the list
  def pop_front(self):
    if(self.head != None):
      temp = self.head
      self.head = self.head.next
      temp = 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