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);
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.