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 = 
    #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): = data = 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
      temp = self.head
      while( != None):
        temp = = newNode

  #Delete first node of the list
  def pop_front(self):
    if(self.head != None):
      temp = self.head
      self.head =
      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(, end=" ")
        temp =
      print("The list is empty.")

# test the code                 
MyList = LinkedList()

#Add four elements in the list.

#Delete the first node

The above code will give the following output:

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