user3764893
user3764893

Reputation: 707

How to delete the first node of a linked list in c++

I have been trying to delete the first node from a single linked list. What I did is as follow

After generating a simple linked list as : 1 - > 2 -> 3 -> 4 -> 5

and calling my method for deleting the first node the result is as not correct. It returns the following linked list: 0 -> 2 -> 3 -> 4 -> 5

I didn't get why does the 0 still exists.

#include <cstdlib>
#include <iostream>

using namespace std;

struct Node
{
    int data;
    struct Node *next;
};

Node* Delete(Node *head)
{
    Node* temp = head;
    head = head->next;
    delete temp;
    return head;
}

int main(void) {

    Node* head = new Node();
    Node*  temp = head;

    for(int i=1; i<=5; i++)
    {
        Node* newNode = new Node();
        newNode->data = i;
        newNode->next = NULL;

        temp->next = newNode;
        temp = newNode;
    }

    Delete( head = head->next );

    while(head != NULL)
    {
        cout<<head->data<<" ";
        head = head->next;
    }
    cout<<endl;     

   return 0;
}

Upvotes: 2

Views: 10132

Answers (4)

lukachu03
lukachu03

Reputation: 1

I think you can write your delete function in a more simpler way. For example you can write it like this:

void Delete(nod * &p)
{
    nod * t = p -> urm;
    p = t;
}

I just want to point out that i am not a native english speaker so the variables might not make sense for you; Here is the explanation: You will reference p because it will change element will change. p = first element; nod = node; urm = next(is a pointer that memorizes the address of the first element). Hope i helped you!

Upvotes: 0

Shakti S
Shakti S

Reputation: 11

I want to highlight two things here-

First : The linked list your code is generating here is 0->1->2->3->4->5

Second : By looking at your code it seems that you intend to call Delete on the 2nd node (head->next) of the linked list and NOT on the first node (head).

However, the way you are calling Delete needs to be corrected first. So, If you want to delete the first node (head) of the linkedlist, call it this way:

head = Delete(head);

And you should be good to go. The output would be : 1->2->3->4->5 (which is correct based on the linked list your creates in the first place)

Hope this helps.

Upvotes: 0

vidal
vidal

Reputation: 1

Furthermore the call to delete is wrong and you mix new and free to manage dynamic memory as people said you before, you have a 0 value because the initial list is 0 -> 1 - > 2 -> 3 -> 4 -> 5. You start head without any initial value and for that head->data is 0.

Upvotes: 0

unxnut
unxnut

Reputation: 8839

You need to change the way you called Delete. It should be

head = Delete ( head );

The way you have your code, you assign head to be head->next and call Delete on head->next,

Upvotes: 5

Related Questions