Deleting Linked List

Hello, I am working on a piece of code that would delete all the nodes in a linked list.

Is this implementation correct?

Thank you in advance

1
2
3
4
5
6
7
8
9
10
  Node* trav = head;
  Node* temp;
  
  while(trav != NULL)
  {
     trav= trav_>next;
     delete temp;
     temp = trav;
  }


Edit: I dont think the very first node is getting deleted
Last edited on
It isn't. You call delete temp; before ever initializing it, and it is initialized to the value of trav only after trav has been "incremented" (trav = trav->next).

Drawing a picture of the linked list and then following through the function step by step is a great way to see if it actually works. When you do this, check for a case when it is empty, when there is only one node, and when there are multiple nodes.

I actually drew this out and followed the loop every step. It seems that at the end, the first node(the original head node) is not deleted. How could i fix this?
Last edited on
Initialize temp to head. That way when the loop is first entered, the node at head will be deleted.
Ok, if I initialize temp to the head, the list would not traverse all the way.
Then you need to change the logic of your loop. The initialization was a hint, but I am not going to write it for you. Logically you want your trav to be pointing at the node ahead of the node temp is pointing to. So the first time through you want trav to move up a node but temp to stay pointing at head so it can delete it before also moving forward.
It's easier if you set and use temp in the same iteration of the loop. So the inside of the loop looks more like this:
1
2
3
temp = trav;
trav = trav->next;
delete temp;

Topic archived. No new replies allowed.