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.
#include <iostream>
#include <cstdlib>
usingnamespace 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;
}
elseif(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;
}