Question about linked list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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?
closed account (48T7M4Gy)
Assuming the list already has at least one node:
1
2
3
4
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 


so you end up with head -> pnew -> old_head ...
Lets say i create a new list

1
2
3
node* temp =  new node; [Temp]
temp->next = head; [Temp]->[Head]
head = temp; [Head]->[Old_Head]

With only one node created
closed account (48T7M4Gy)
For an empty list:

1
2
3
Node *pNew = new Node;
head = pNew;
tail = pNew; // that's if you want your list have a tail 


Keep in mind that the head and tail aren't Nodes, they are pointers to Nodes.
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

and finally head is moved:
0 1 2 3 4
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.
closed account (48T7M4Gy)
head = temp means those two pointers have the same value which in this scenario is the address of some Node Node_A, for arguments sake.

If temp points to Node_A (which has an address of say 1234) then head has the same value i.e. 1234 i.e. head points to Node_A also.

One way to satisfy yourself is print out head and temp
cout << head << ' ' << temp;
Topic archived. No new replies allowed.