Stack Overflow Asked by ilmoi on January 17, 2021
I’m following the tutorial over here to build a linked list. I can’t get the "Adding an item to the beginning of the list (pushing to the list)" part to work.
My code:
node_t* prepend(node_t **head, int val) {
//create new node pointer
node_t *new_node = (node_t*) malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head; //set its next to existing head (pointer of pointer)
//update existing head to point to new node
*head = new_node;
return *head;
}
int my_first_ll() {
//define a local variable called head that will point to the first node
node_t *head = NULL;
head = (node_t*) malloc(sizeof(node_t));
//check for null pointer
if (head == NULL) {
return 1;
}
//note how because head is a pointer we're using -> rather than dot notation to access attributes
head->val = 1;
head->next = (node_t*) malloc(sizeof(node_t));
head->next->val = 2;
head->next->next = NULL; //last item should point to a NULL
head = prepend(head, 0);
print_list(head);
}
It prints:
Currently at node 0
Instead of
Currently at node 0
Currently at node 1
Currently at node 2
So it seems when I insert the new head I fail to link to the previous one – but I just can’t figure out how.
You can pass **head
to the function, so you basically pass a pointer to a pointer:
void prepend(node_t **head, int data){
node_t *new = malloc(sizeof(node_t));
//set data
new->data = data;
//set the next pointer of new to current head
new->next = *head;
//now set the newly created node to be the new head
*head = new;
}
But the you'd have to call the function like this:
int main()
{
node_t *head = NULL;
prepend(&head, 3);
prepend(&head, 6);
printlist(head);
deltelist(&head);
return 0;
}
And theres no reason to return the *head
in your function because you basically change the head node you created in main.
So if I now print my list, it prints
6
3
And never forget to delete the list after you used it.
Hope this helped you :)
Answered by megaftw on January 17, 2021
I found a solution: instead of passing **head
to prepend
like they do in the tutorial, passing *head
solves it. Thus the final code:
node_t* prepend(node_t *head, int val) {
//create new node pointer
node_t *new_node = (node_t*) malloc(sizeof(node_t));
new_node->val = val;
new_node->next = head; //set its next to existing head (pointer of pointer)
//update existing head to point to new node
head = new_node;
return head;
}
Could someone explain why one works and the other doesn't? And why did they use two stars in the tutorial? And if two stars is actually correct, then why is it failing for me?
Answered by ilmoi on January 17, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP