Omar Abdelsalam
Omar Abdelsalam

Reputation: 47

The first element in the created list is always 0

I don't yet understand fully how linked lists and nodes in C/C++ work, but this is the function I use to add nodes to a list.

void AddNode(Node* head, int new_data) 
{ 
    Node* new_node = new Node(); 

    Node *last = head;

    new_node->data  = new_data; 

    new_node->next = NULL; 

    if (head == NULL) 
    { 
       head = new_node; 
       return; 
    }   

    while (last->next != NULL)
    {
        last = last->next;
    }
        last->next = new_node; 


}

The first element in the list will always be 0, what am I doing wrong?

Upvotes: 1

Views: 131

Answers (2)

lisuwang
lisuwang

Reputation: 18

In c++ , you must update Node *last = head; to Node *& last = head;

In C, you must update Node *last = head; to Node ** last = head;

Upvotes: 1

上山老人
上山老人

Reputation: 462

I used the function AddNode as bellow:

Node* head = new Node();
AddNode(head, 1);

And i get the same problem like you.Because the first element will never change.There are two modify (1) return the head

Node* AddNode(int new_data) 
{ 
    Node* head = NULL;
    Node* new_node = new Node(); 

    Node *last = head;

    new_node->data  = new_data; 
    cout << "-->" << new_node->data << endl;

    new_node->next = NULL; 

    if (head == NULL) 
    { 
       head = new_node; 
       return head; 
    }   

    while (last->next != NULL)
    {
        last = last->next;
    }
        last->next = new_node; 

    return head;
}

use like this:

Node* head = AddNode(1);

(2)pass the head address,because you want to change it

void AddNode(Node** head, int new_data) 
{ 
    Node* new_node = new Node(); 

    Node *last = *head;

    new_node->data  = new_data; 
    cout << "-->" << new_node->data << endl;

    new_node->next = NULL; 

    if (*head == NULL) 
    { 
       *head = new_node; 
       return; 
    }   

    while (last->next != NULL)
    {
        last = last->next;
    }
        last->next = new_node; 
}

use lie this:

Node* head = NULL;
AddNode(&head, 1);

Hope it's useful for you.

Upvotes: 0

Related Questions