Search code examples
c++functionlinked-listadditionunordered

Adding nodes in an Unordered Linked List


I just want to know the difference between these two lines. listData is head by the way.

temp->next = listData;

and

listData = temp->next;

Here is the full code for adding a node to an unordered linked list

NodeType* temp;
temp = new NodeType;
temp->data = item;
temp->next = listData;
listData = temp;
length++;

So if I did listData = temp->next instead of temp->next = listData what would happen or can somebody explain in simplest terms what it means. Everytime I see the -> on the right or left side it gets me confused. Thank you!


Solution

  • The -> simply indicates that you are accessing a pointer reference, nothing more and nothing less.

    When you see an equal sign, it means whatever is on the right side is assigned to the left side (unless you override the equal sign), which you normally wouldn't do.

    1. temp->next = listData

    You are setting the listData as the next of temp.

    1. listData = temp->next

    You are setting next of temp as listData

    Since you are adding a node named temp to a LinkedList, you would want the former. Think of a linked list and you are adding a node temp between two nodes A and B. You would:

    1. Set next of A to temp

    2. Set next of temp to B

    The latter of this process is what temp->next = listData is doing. (I'm assuming listData is the rest of the linked list after and including B.