0

Adding new node to linked list not working properly (C)

I'm working on this code that should create a linked list and the output should be 13 88 71 5 3, but there's something wrong in the function that adds a node in a defined position. https://code.sololearn.com/cSHalv3tFY9d/#c

21st Jun 2020, 8:29 AM
Guido Parlatore
Guido Parlatore - avatar
3 odpowiedzi
+ 1
Guido Parlatore "cur=n" is the culprit. As it's a local variable, any writes to it are lost when the function ends. I think it should be cur->prev->succ = n; This updates variables not bound to the function, so their changes aren't lost. It would only work on pos != 0, though. (The first node has prev=NULL.)
21st Jun 2020, 9:07 AM
Felipe BF
+ 1
Hello! :D Please use an auxiliary variable inside "listinpos", that has "*a" as its initial value. nodo *cur = *a; Perform all manipulations over "cur" instead of "*a", especially when finding the node where to append. The changes will be honored as these pointers are being accessed from a known reference ("a") and aren't bound to the function (as parameters, I mean). Doing it the way you're doing it completely obliterates the original list. Either do that, or pass "a" by value (single pointer). Here, the address where "a" points to won't be changed---except if you want to add a node before the first element, but we got that function already.
21st Jun 2020, 8:45 AM
Felipe BF
+ 1
I changed the function to look like this but its not working? have i understood you wrong? void listinpos(nodo **a,int pos,int q){ nodo* n=malloc(sizeof(nodo)); nodo* cur=*a; n->valore=q; for(int i=0;i<pos;i++){ cur=(cur)->succ; } n->prec=(cur)->prec; n->succ=cur; cur=n; }
21st Jun 2020, 9:03 AM
Guido Parlatore
Guido Parlatore - avatar