Write a function that takes a linked list, deallocates all of its memory, and sets its head pointer to NULL (the empty list).

The idea is to iterate through the list and delete each node encountered. There is a slight complication inside the loop since we need to extract the .next pointer before deleting the node since it will be technically unavailable after the delete.

The algorithm can be implemented as follows in C and C++:

C


Download  Run Code

Output:

Deleting 1
Deleting 2
Deleting 3
Deleting 4
Deleting 5
List deleted

C++


Download  Run Code

Output:

Deleting 1
Deleting 2
Deleting 3
Deleting 4
Deleting 5
List deleted

We can easily convert the above iterative version into a recursive one. Following is the simple recursive implementation in C and C++:

C


Download  Run Code

Output:

Deleting 5
Deleting 4
Deleting 3
Deleting 2
Deleting 1
List deleted

C++


Download  Run Code

Output:

Deleting 1
Deleting 2
Deleting 3
Deleting 4
Deleting 5
List deleted

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and requires extra space for the call stack.

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf