user13814958
user13814958

Reputation: 1

These two code snippets are similar but show different results

first code snippet

void insert_last(Node* head,int new_data)
{
    Node* new_node = new Node();
    new_node->data = new_data;
    new_node->next = NULL;

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

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

and the second one :

void insert_last(Node** head,int new_data)
{
    Node* new_node = new Node();
    new_node->data = new_data;
    new_node->next = NULL;

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

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

The class is called Node with two data members

  1. data (type=int)
  2. *next (type = Node)

What is the reason that these two code snippets show different results when they are called and which one to use ?

Upvotes: 0

Views: 50

Answers (2)

user
user

Reputation: 944

Node**head is a pointer to a pointer, Node*&head2 is a reference to a pointer, so Node**head will pass a pointer to a pointer by value.

In the first snippet you passed a pointer by value, changing this pointer inside the function will not change the pointer that was passed to the function. In the second snippet you pass a pointer to a pointer by value. Changing the dereferenced pointer to pointer (which you do) : *head = new_node; will effectively change the pointer to Node that is being pointed to.

In the first snippet head = new_node; you are changing the value of a pointer that was being passed by value, the change to this pointer is only local. Had you passed this pointer by reference like this :

void insert_last(Node* &head,int new_data)

Then the two functions would behave the same

Upvotes: 1

Cory Crowley
Cory Crowley

Reputation: 324

I'm also fairy new to C++, but this is what I think.

Passing Node** head will pass a pointer to a pointer, ensuring that the head pointer is changed outside of the local scope as well.

Check out passing pointers by reference.

In the first code_snippit, I believe that you'd need to return the updated head pointer for the desired result, while the second snippit modifies the data outside of the local scope.

Upvotes: 1

Related Questions