Deleting a Linked List in C++

This article discusses a method and a program for deleting a linked list in C++. A linked list may be entirely removed by deleting all its nodes. We may do this by traversing through the list, node-after-node.

As mentioned earlier, the approach to solve this problem is to remove all of the nodes from the linked list, one after the other. This can be done by traversing through the linked list.

Here, we first create a linked list and continuously add elements into it until the user decides to stop. We now traverse through the linked list. At each node, we increment the start pointer to the next node and delete the node it previously pointed. This is continued till the start node points to NULL. In other words, until the end of the list.

Now, have a look at the code below:

#include<iostream>

using namespace std;

int counter = 0;

struct node
{
    int number;
    node *next;
};

node *start = NULL, *temp = NULL;

node *create(int num)
{
    node *newnode = new node;

    newnode -> number = num;
    newnode -> next = NULL;

    return newnode;
}

void insertNode(int value)
{

    if(start == NULL)
    {
        start = temp = create(value);
    }

    else
    {
        temp -> next = create(value);
        temp = temp -> next;
    }

}

void display()
{

    node *tempPtr = start;

    while(tempPtr != NULL)
    {
        cout<<tempPtr -> number<<" -> ";
        tempPtr = tempPtr -> next;
    }

    cout<<" NULL"<<endl<<endl;

}

int main()
{
    node *delptr = NULL;

    int num;
    int index;
    char ch;

    do
    {
        cout<<"ENTER NUMBER : ";
        cin>>num;

        insertNode(num);
        counter++;

        cout<<"DO YOU WANT TO CONTINUE ?";
        cin>>ch;

    }while(ch == 'y' || ch == 'Y');

    display();

    cout<<"TOTAL NUMBER OF NODES : "<<counter;

    while(start != NULL)
    {
        delptr = start;
        start = start -> next;

        cout<<"DELETED NUMBER : "<<delptr -> number<<endl;

        display();

        delete delptr;
    }

    return 0;
}

 

In the above code, as we traverse through the linked list, a pointer named ‘delptr’ temporarily points to the node. Then we increment the start pointer. After that, we delete the link to the memory block pointed by the ‘delptr’ pointer. However, this does not remove the pointer from the memory.

The ‘new’ operator is used for dynamic allocation of memory. This puts the variables in the heap. On the other hand, a delete operator deallocates the memory from the heap. Again, it is important to recall that the pointer to the object is not destroyed, only the value of memory block it points to is destroyed. The free() operator is used for the same purpose, but when the memory is allocated using calloc(), malloc() or realloc() operators.

Now, feel free to read the following articles:

 

Leave a Reply

Your email address will not be published. Required fields are marked *