Posted on by Kalkicode
Code Single linked list

Delete all nodes in a linked list

The problem revolves around deleting all nodes in a linked list. Given a singly linked list, the task is to delete all the nodes present in the list, effectively making the linked list empty. This is often done to deallocate memory and clear the linked list.

Problem Description

Given a singly linked list, the problem is to remove all the nodes in the list, making it empty.


Consider the following linked list:

1 -> 2 -> 3 -> 4 -> 5 -> 6

After deleting all nodes, the linked list will be empty:

Empty Linked List

Idea to Solve the Problem

To solve this problem, we need to traverse through the linked list and free the memory allocated for each node. This is achieved by iterating through the linked list and deallocating memory for each node one by one.


    temp = linkedList.head
    while temp is not NULL:
        linkedList.head =
        temp = linkedList.head

Algorithm Explanation

  1. Start with the temp pointer pointing to the head of the linked list.
  2. Traverse through the linked list using the temp pointer: a. Update the head of the linked list to b. Free the memory occupied by the current node temp. c. Move the temp pointer to the new head of the linked list.
  3. Continue this process until the temp pointer becomes NULL, indicating that all nodes have been deleted.

Code Solution

Time Complexity

The time complexity of this algorithm is O(n), where n is the number of nodes in the linked list. We traverse through each node once to free its memory.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment