I am learning linked list operations and have a question related to parameter passing.
Question 1: I am creating a simple linked list with three values 1->2->3. And am trying to print it. Below is my code. I am creating a node "first" in my main and am passing it to the method "createlinkedlist". I am using a pointer "head" and updating it within the method. But I see that the values of "head" are retained correctly outside the method "createlinkedlist". I dont understand how this is happening. I was thinking I should use referencial parameter passing like
void createLinkedList(struct node * & head) or void createLinkedList(struct node ** head)
instead of
void createLinkedList(struct node * head)
to get the correct values reflected outside the function. What am I missing here? Why am I able to see the correct values inside the printList method?
struct node
{
int data;
struct node * next;
};
void createLinkedList(struct node * head)
{
struct node * second = (node *)malloc(sizeof(node));
struct node * third = (node *)malloc(sizeof(node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
}
void printList(struct node * first)
{
struct node * current = first;
while(current)
{
printf("%d",current->data);
current = current->next;
}
}
void main()
{
struct node * first = (node *)(malloc(sizeof(node)));
createLinkedList(first);
printList(first);
}
Question 2: I am using the same program as above , but adding a push function
void push(struct node *& first, int data)
{
struct node * newnode = (node*)malloc(sizeof(node));
newnode->data = data;
newnode->next = first;
first = newnode;
}
Now I see that unless I use a "&" for the first parameter in the push(), I am not able to see the updations in the printList method. It makes sense to me because we usually need to use a referncial parameter to make the local function changes seen outside the function. So if the list expects a referencial parameter here, why does it behave differently in the question 1 case.? Pls. let me know.