Reputation: 23
I created a linked list and wanted to print the items.
struct node{
int item;
node *next;
}; typedef node* nodeptr;
void insertAt(nodeptr headnode, size_t index, int item);
int main(int argc, const char * argv[]) {
nodeptr head;
head = new node;
nodeptr constructor = new node;
head->item = 0;
head->next = constructor;
for(int n = 0; n<8; n++){
constructor->item = n+1;
constructor->next = new node;
constructor = constructor->next;
}
constructor->item = 9;
constructor->next = new node;
constructor->next = nullptr;
for(nodeptr begin = head; begin != nullptr; begin = begin->next){
cout << begin->item << endl;
}
return 0;
}
If I write my code as this, it works fine (print 0123456789). But after making a slight change after the for loop:
constructor->item = 9;
constructor->next = new node;
constructor = constructor->next;
constructor = nullptr;
I assumed this would work the same way. but the output is 01234567890 with a one more 0 added. Can anyone tell me why?
Thank you so much for help!
Upvotes: 0
Views: 57
Reputation: 1826
In the first case, you make the constructor->next point to the new node created, and then to the nullptr. This is where the new node is lost. That is , the node that is pointed by the constructor currently,which is 9 in this case, its next will point to the new node first, and in the next line, its reference is changed to the nullptr. In the second case after creating the new node, you move you pointer constructor to the node to the next of 9. So when you say next of constructor now, it implies the next of the newly created node, to which the constructor pointer is pointing. The value zero would be initialised by default when you create a new node. So the newly created node is not lost in the second case.
Upvotes: 0
Reputation: 20919
You've added a new node after the 9
entry but never defined the item
value.
The value happened to default to zero.
As to the difference between
// Creates a new node...
constructor->next = new node;
// Then ignores it by making the current position the end of the list
constructor->next = nullptr;
and
// Creates a new node...
constructor->next = new node;
// Makes the new node the current node
constructor = constructor->next;
// Marks the current position as the end of the list
// The list is now one item longer than the previous example
constructor = nullptr;
the comments should help explain the difference.
They both create a new node, but in the second block, the constructor = constructor->next;
moves to the new node before marking the end of the list. The end result is that the second block of code has one more node in the list than the first block.
Upvotes: 3