Reputation: 518
In this code:
void push(node **head, int data) {
node *temp = malloc(sizeof(node));
temp->data = data;
temp->next = *head;
*head = temp;
}
Why is temp->next = *head
not enough?
Why is it necessary to set *head
equal to temp
? What does that accomplish, exactly?
Upvotes: 1
Views: 48
Reputation: 8422
The method push()
takes two arguments: a pointer to a pointer to a node
(which is a pointer to the linked list) and a value to insert into the list.
The reason why *head = temp;
is necessary is so that the caller's linked list ends up getting modified. Without this line, the caller's linked list is not modified.
Here's a highly simplified example of why this is necessary. Let's say I have a method that modifies an int:
void foo(int *bar) {
int baz;
baz = *bar;
baz = 42;
}
After I call foo()
by passing in a pointer, nothing will happen to the variable the pointer is pointing to. When foo()
finishes, all the stack variables (i.e. bar
and baz
) will go out of existence and the modification made to the value of bar
is never saved).
Back to the example in your question. If that line never gets called, nothing will happen to the caller's copy (i.e. after calling the function, it will be as if the element was never added to the list) for the same reason that the caller's copy of whatever got passed into foo()
wasn't changed.
For this reason, you often see a different method signature for the insert()
function:
node *push(node *head, int data);
This gets called like this:
// assume head is a pointer to a node
head = push(head, 42);
The effect is the same, but since there's only a pointer to a node getting passed in, whatever push()
does to the list's structure doesn't get applied to head
until the assignment takes place.
Upvotes: 2
Reputation: 9386
Assuming it is a list-based stack (guess based on the Push
operation) then the item should be added to the beginning of the list so it can be easily popped.
This way, when the caller would try to use the stack again the head of the list would be updated with the new data item.
Upvotes: 0
Reputation: 331
It resets the head to the new node allowing us to iterate over all the elements. Push is placing the new node at the beginning of the list. Head is like a starting point for a linked list using which you can get to all the elements. If the head is not set to the new node you will loose the reference to the newly inserted data leading to memory leaks.
Upvotes: 1