Delete a Linked List in C

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 extract the .next pointer before we delete the node, since after the delete it will be technically unavailable.

C

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

Download   Run Code

Output:

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

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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂


Leave a Reply

avatar
  Subscribe  
Notify of