+ 1
need help understanding linked lists
for the first time today i'm learning how to create linked lists, so i need some help understanding. here's the code: https://code.sololearn.com/cMOemv3GkDBy my question: -what is that if and else statement specifically meant to do in the node creation segment? i understand part of it, being that you add the node to the end and set it's value equal to null, but what does the "tail = newNode" part mean? am i re assigning the address? does it take up all both the data and the value?
2 Answers
+ 2
With 'tail->next = newNode' you say that you link the new node to the currently last node, since you inserted something into the list, so you must link it to the list, otherwise you can't access it. After that, you basically tell that the newly created node is the new last (tail) node.
Yes, you reassign the address, so that the 'tail' pointer points to the newly created node. Data movement (other than the pointer's) does not occur.
For example:
--------------------------
List before insertion:
head -> node1 -> node2 (tail)
List after 'tail->next = newNode':
head -> node1 -> node2 (tail) -> newNode
List after 'tail = newNode':
head -> node1 -> node2 -> newNode (tail)
+ 1
You are creating three lists with one element in the list with:
LinkedList L;
L.CreateNode(12);
L.displayNodes();
LinkedList a;
a.CreateNode(15);
a.displayNodes();
LinkedList b;
b.CreateNode(25);
b.displayNodes();
Use this to make one list with 3 elements:
LinkedList L;
L.CreateNode(12);
L.CreateNode(15);
L.CreateNode(25);
L.displayNodes();