Deleting a linked list

Hi,
If I have a linked list, how can I delete it at the end of my program to free the memory taken up. I know I have to use delete but not sure how to use it in this case. Help me out on this please.

Here is the code that I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <cstdlib>

using namespace std;

struct Numlist
{
    int num; //Number
    Numlist * next; //Pointer to the next node
};

int main()
{
    srand(time(0));

    Numlist * mainList;
    Numlist * navigator;

    mainList = new Numlist;
    navigator = mainList;

    //Keep on making a new list and add values until number of lists is 5.
    for(int i = 0; i < 5; i++)
    {
        if(i <= 3)
        {
            navigator->num = rand() % 100;
            navigator->next = new Numlist;
            navigator = navigator->next;
        }
        else if(i == 4)
        {
            navigator->num = rand() % 100;
            navigator->next = NULL;
        }
    }

    //Set the navigator back to the beginning of the list
    navigator = mainList;

    //Print out the values from the list
    for(int j = 0; j < 5; j++)
    {
        cout << "Number in list " << j+1 << ": " << navigator->num << endl;
        navigator = navigator->next;
    }

    return 0;
}
Last edited on
Line 42: while ( NULL != navigator )
Operate based on what really is in the list rather than by hardcoded parameters.


Deletion:
1. Numlist could have a destructor that deletes next. Then delete mainList.
or
2. Loop through the list like when printing.
1
2
3
4
5
{
  auto victim = navigator;
  navigator = navigator->next;
  delete victim;
}
Hey keskiverto! Thanks for your reply. Could you demonstrate solution method #1? Thanks :).
Allright, thanks for your help! :)
Topic archived. No new replies allowed.