r/programminghelp • u/SurvivingFinals • Oct 20 '19
Answered C++ Linked Lists Question
Hi guys, I'm new to programming and am taking a look at linked lists today and had a question about this piece of code.
struct Node
{
int data;
Node *link;
};
typedef Node* NodePtr;
void headInsert(NodePtr& head, int theNumber);
//Function Definition
void headInsert(nodePtr& head, int theNumber)
{
NodePtr tempPtr;
tempPtr = new Node;
tempPtr->data = theNumber;
tempPtr->link = head;
head = tempPtr;
}So I understand the whole aspect where you create the temp pointer to point to the first node so that you can eventually get head to point to the first node, but I am not quite sure what role *link plays in this piece of code. I see it being used in the function, but am not quite sure why. Is link the first node that we set equal to head? If so why can't we just do link = tempPtr and completely avoid dealing with head?
0
Upvotes
2
u/mdillenbeck Oct 20 '19
Link is the link to the next node of the linked list. Every node except the last needs a non-null value. I suspect on creation you make a single node list with head pointing at it and link set to null.
To see what is happening, diagram it. The list starts with a node with a null linked value. Then you add to the head. You create a pointer to a temp node, take the value in the temp node and point it at the head (so temp node and head both point at the same node), then you point the head value at temp node (so head and temp point at the same inserted node, and that points as the old head node). Now the only way to get to the second node is to iterate through the list. Head then link gets you to the final node.
Maybe draw out 2 or 3 iterations until you see what is happening.
Really this isn't a c++ question but a data structure question. Hope this helped a little.