deleting a linked list

ok so this is what i wrote for deleting a whole linked list...can someone check on it and tell me if it will work?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//assuming my struct list is declared already somewhere ;)
  void delete_list( list* & head)
{ list * temp, * temp1;
temp = head;
temp1 = temp->next;

while (temp1->next != 0)
      { temp->next = temp1->next; 
        delete temp1;
       list * temp1;
      }
else { delete temp1;
       temp->next = 0;
       delete head;
      }
No. There is no such thing as a while-else construct in C++.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//use this pointer to delete nodes
Node* tempDel = head;

//keep a reference to the next node to delete
//so you don't lose it when you call delete on
//the other pointer
Node* tempNext = nullptr;

while (tempDel)
{
    tempNext = tempDel->next;
    delete tempDel;
    tempDel = tempNext;
}

I'm assuming that head will be null if the list is empty, so if you pass in an empty list the 'while' block will never execute and you won't attempt to free a null pointer.
Last edited on
Topic archived. No new replies allowed.