Delete Linked List

Write a function that takes a linked list, deallocates all of its memory and sets its head pointer to nullptr (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 extract the .next pointer before we delete the node, since after the delete it will be technically unavailable.

 
C++ implementation –
 

Download   Run Code

Output:

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

 

Recursive solution –

We can easily convert above iterative version to recusive one. Below is simple recursive implementation –

 
C++ implementation –
 

Download   Run Code

Output:

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

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz