Linked List question

Why does my insertFront function display 5 10 20 30 35 40 but when I return from the function and call display is shows 10 20 30 35 40.
#include <iostream>

using namespace std;

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

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

// apending
void addNode(struct Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;

while(head) {
if(head->next == NULL) {
head->next = newNode;
return;
}
head = head->next;
}
}
void insertFront(struct Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = head;
head = newNode;
while(head) {
cout << head->data << " ";
head = head->next; //next item in the linked list
}
cout << endl;
cout << endl;
}
void display(struct Node *head) {
// while list is not null loop
while(head) {
cout << head->data << " ";
head = head->next; //next item in the linked list
}
cout << endl;
cout << endl;
}
int main()
{
struct Node *head = new Node;
initNode(head,10);
display(head);

addNode(head,20);
display(head);

addNode(head,30);
display(head);

addNode(head,35);
display(head);

addNode(head,40);
display(head);

insertFront (head,5);
display(head);
return 0;
}
Last edited on
That it would be clear let consider a simple code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

void f( int x )
{
   x = 10;
   std::cout << "x = " << x << std::endl;
}

int main()
{
   x = 5;

   std::cout << "x = " << x << std::endl;

   f( x );

   std::cout << "x = " << x << std::endl;
}


The output will be

5
10
5


Variable x in main was not changed after the call of function f because within the function a copy of variable x was used.

The same is valid in your case.


void insertFront(struct Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = head;
head = newNode;
// other stuff

Here head is a copy of variable with the same name defined in main. So in this function you are changing the copy. The original variable will be unchanged.
Last edited on
That's what I thought but my addNode changed a copy of head and the head from main was also modified. Why is that?
Last edited on
You are mistaken. Function addNode does not change head itself. It only link a new node to data member next.
Thank you very much.
Topic archived. No new replies allowed.