When adding a node to the end of a linked list, the process below is used to find the last node and append a new node after it:
The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till end and then change the next of last node to new node. (https://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/)
However, I am a bit confused as to how pointers actually work in this context. For example, when I do something like this:
int test = 4;
int pointer = test;
pointer += 1;
The value of test does not change, only the value of the pointer does. However, when adding a node to a linked list, a temporary pointer is used as follows:
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
So essentially, at the very end, the last
pointer is set equal to the last element of the linked list. Its next
node is set equal to the new node being created. What I am confused about is how this impacts the original linked list. Wouldn't this simply set the next node of the pointer last
rather than the actual next node of the last node of the linked list (in a similar manner as demonstrated with my int test
above)?