Sudhanshu Singh
Sudhanshu Singh

Reputation: 41

Linked list Behaviour

Can Someone please explain the difference in Behaviour ?

#include <iostream>
using namespace std;
struct Node {
    int data;
    Node* next;
};

// only for the 1st Node
void initNode(Node *head,int n){
    head->data = n;
    head->next =NULL;
}

void insertFront(Node *head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = head;
    head = newNode;
}

void display(Node *head) {
    Node *list = head;
    while(list) {
        cout << list->data << " ";
        list = list->next;
    }
    cout << endl;
    cout << endl;
}


int main() 
{

    Node *l1 = new Node;

    initNode(l1,10);
    display(l1);
    insertFront(l1,5);
    display(l1);
    insertFront(l1,6);
    display(l1);
    insertFront(l1,7);
    display(l1);

    return 0;
}

Some how the nodes are not linking. The output is : 10

10

10

10

If The program is coded using pointer to a pointer as below then it works fine. what am is missing ?

#include <iostream>
using namespace std;
struct Node {
    int data;
    Node* next;
};

// only for the 1st Node
void initNode(Node *head,int n){
    head->data = n;
    head->next =NULL;
}

void insertFront(Node **head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = *head;
    *head = newNode;
}

void display(Node *head) {
    Node *list = head;
    while(list) {
        cout << list->data << " ";
        list = list->next;
    }
    cout << endl;
    cout << endl;
}


int main() 
{

    Node *l1 = new Node;

    initNode(l1,10);
    display(l1);
    insertFront(&l1,5);
    display(l1);
    insertFront(&l1,6);
    display(l1);
    insertFront(&l1,7);
    display(l1);

    return 0;
}

Output correct as expected :

10

5 10

6 5 10

7 6 5 10

Upvotes: 0

Views: 64

Answers (1)

francis
francis

Reputation: 9817

In the first case, in function

void insertFront(Node *head, int n) {
  Node *newNode = new Node;
  newNode->data = n;
  newNode->next = head;
  head = newNode;
}

head is a copy of the pointer l1 used in the scope of main(). When head is modified, l1 is left unchanged. This is the reason why a pointer to l1 (&l1) is passed to the function in the second case void insertFront(Node **head, int n). Then *head is l1, not just a copy of l1.

First case is an example of passing argument by value, and the second case is passing an argument by reference What's the difference between passing by reference vs. passing by value?

For instance, the following function is basically useless :

void useless(int a){
  a=42;
}

If int b=2;useless(b);cout<<b<<endl; is called it will print 2, not 42.

The following function is the right way to go :

void rightwaytogo(int*a){
  *a=42;
}

Don't forget to write a function to delete the nodes of your linked list.

Upvotes: 1

Related Questions