I'm studying lists currently (trying to recreate them) and I came across a weird problem. Here's my struct:
struct listNode{
listNode(int n, listNode* ne = NULL){
value = n;
next = ne;
}
int value;
listNode* next;
};
listNode* head = NULL;
Now I made a function to add an element to the bottom:
void add(int n){
if(head == NULL){
head = new listNode(n);
return;
}
listNode* n1 = head;
while(n1 != NULL){ //Should be: while(n1->next != NULL){
n1 = n1->next;
}
n1 = new listNode(n); //Should be: n1->next = new listNode(n);
}
But this isn't adding any element past the head. Now, I already figured out the solution (see comments above) my problem is that I do not understand why my first function didn't work.
I'll explain what I understood with a scheme:
The Beginning
HEAD = NULL;
I add 1
HEAD = [1, NULL];
I add 2
The while loop arrives at the last element (where "next" is NULL) and creates in it the new element
HEAD = [1, new listNode(2)];
Result
HEAD = [1, POINTER] [2, NULL];
Now, why n1 after the while loop isn't what I wan't it to be?
int n = 5; int m = n; m = 7. Do you expectnshould become 7? Don't think so. But nevertheless you sayn1 = n1->next; n1 = new listNode(n);and expect thenextmember of previousn1to change. Weird, huh? - n. 1.8e9-where's-my-share m.n1 = n1->next;n1is null I want it to point to the new element - Xriuknextof the last element. Before saying "but n1 is the attributenextof the last element", look again atm = n; m = 7. Are you assigning 7 ton? - n. 1.8e9-where's-my-share m.