Node list

Can any body explain to me easily why head = current changed to current = head on the second part?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

	nodeType *head = NULL; // 1
	nodeType *current;

	printList(head);

	// 2: insert number 100 to  as first node
	current = new nodeType;
	current->info = 100;
	current->link = NULL;
	head = current;
	printList(head);

	// 3: insert number 200 before number 100
	current = new nodeType;
	current->info = 200;
	current->link = head;
	head = current;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    nodeType *head = NULL;          // head points to null
    nodeType *current;              // current points to garbage

    printList(head);

    // 2: insert number 100 to  as first node
    current = new nodeType;         // 'new' creates a new node.  Call it 'foo'.
                                    //   Now, current points to foo.  head points to null
    current->info = 100;            // foo.info = 100
    current->link = NULL;           // foo.link points to null
    head = current;                 // head points to whatever current points to.  So now, head and current both point to foo.
    printList(head);

    // 3: insert number 200 before number 100
    current = new nodeType;         // 'new' creates a new node.  Call it 'bar'
                                    //   Now, current points to bar, head points to foo
    current->info = 200;            // bar.info = 200
    current->link = head;           // bar.link points to whatever head points to (foo)
    head = current;                 // head points to whatever current points to (bar)
    
/*
    After all that:
    
    2 objects, foo and bar:
    
    foo:
    {
        info == 100
        link == points to null
    }
    
    bar:
    {
        info == 200
        link == points to foo
    }
    
    
    And 2 other pointers:
    
    current == points to bar
    head    == points to bar
    
    
    ========================
    
    The final goal being, 'head' points to the first element in the list (bar).  Then that element points to the next
    element in the list (foo).
    
    So
    head -> bar
    bar.link -> foo
    foo.link -> null  (indicating there are no more nodes in the list)
*/
Last edited on
Thank you so much Disch!! That was very understandable.
Topic archived. No new replies allowed.