Python Data Structures - Linked List Other Related Topics

Python - Delete all nodes of the Linked List



Deleting all nodes of a linked list requires traverse through the list and deleting each node one by one. It requires creating a temp node pointing to the head then move the head to head next. After that delete the temp node. Repeat the process till the head becomes null.

The function deleteAllNodes is created for this purpose. It is a 2-step process.

def deleteAllNodes(self):

  #1 & 2. create a temp node, if the head is not  
  #   null make temp as head and move head to head 
  #   next, then delete the temp, continue the 
  #   process till head becomes null
  while (self.head != None):
    temp = self.head
    self.head = self.head.next
    temp = None

  print("All nodes are deleted successfully.")    

The below is a complete program that uses above discussed concept of deleting all nodes of a linked list which makes the list empty with size zero.

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

#class Linked List
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 all nodes of the list
  def deleteAllNodes(self):
    while (self.head != None):
      temp = self.head
      self.head = self.head.next
      temp = None
    print("All nodes are deleted successfully.")  

  #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)

#Display the content of the list.
MyList.PrintList()

#delete all nodes of the list
MyList.deleteAllNodes()

#Display the content of the list.
MyList.PrintList()

The above code will give the following output:

The list contains: 10 20 30 40 
All nodes are deleted successfully.
The list is empty.