struct node{
node* next;
int data;
};
class List{
public:
void addFront(){
node* temp = new node;
temp->next = head;
head = temp;
}
private:
node* head;
};
I'm trying to visualize how addFront works. I understand that I created a temp node pointer and set the next node as the head node. The problem is the line head = temp; I'm trying to wrap my head around this line of code. Is the head node now temp as in the node that was originally temp is now the head, and the old head is just a random node? Or since they are pointers, head node points to the address of the temp node, therefore if the list see head it'll look at the address of temp node?
Node* pNew = new Node; // an unconnected new Node
Node *temp = head; // 'disconnect' existing head (old_head)
pNew->next = temp; // 'connect' new Node to old_head
head = pNew; // update head to point to new Node
there are many animations, drawings, videos, and interactive list programs on the web that you can use to see what is happening better.
what you are doing in the insert in front algorithm is this:
say you have this list with head @ 1
1 2 3 4
H
add 0 in front:
temp = new, holds zero, ok.
temp next is head, which attaches 0 to the front as 0's next is 1 now
0 1 2 3 4
T H
What I originally had problems visualizing was the last snippet head = temp. To me it was more intuitive for it to be temp = head because temp was the new head, but I think I realized the problem. I defined head as node* head which is just a node pointer. So if I do head = temp I'm just putting the name "head" on to temp, rather than head pointing to whatever temp was.