@@ -2,43 +2,52 @@ package main
2
2
3
3
import "fmt"
4
4
5
+ /* v is the value of node; next is the pointer to next node */
5
6
type node struct {
6
7
v int
7
8
next * node
8
9
}
9
10
11
+ /* first node, called head. It points from first node to last node */
10
12
var head * node = nil
11
13
12
14
func (l * node ) pushFront (val int ) * node {
15
+ /* if there's no nodes, head points to l (first node) */
13
16
if head == nil {
14
17
l .v = val
15
18
l .next = nil
16
19
head = l
17
20
return l
18
21
} else {
22
+ /* create a new node equals to head */
19
23
nnode := new (node )
20
24
nnode = head
21
-
25
+ /* create a second node with new value and `next -> nnode`
26
+ * is this way, nnode2 is before nnode
27
+ */
22
28
nnode2 := & node {
23
29
v : val ,
24
30
next : nnode ,
25
31
}
32
+ /* now head is equals nnode2 */
26
33
head = nnode2
27
34
return head
28
35
}
29
36
}
30
37
31
38
func (l * node ) pushBack (val int ) * node {
39
+ /* if there's no nodes, head points to l (first node) */
32
40
if head == nil {
33
41
l .v = val
34
42
l .next = nil
35
43
head = l
36
44
return l
37
45
} else {
46
+ /* read all list to last node */
38
47
for l .next != nil {
39
48
l = l .next
40
49
}
41
-
50
+ /* allocate a new portion of memory */
42
51
l .next = new (node )
43
52
l .next .v = val
44
53
l .next .next = nil
@@ -50,9 +59,11 @@ func (l *node) popFront() *node {
50
59
if head == nil {
51
60
return head
52
61
}
53
-
62
+ /* create a new node equals to first node pointed by head */
54
63
cpnode := new (node )
55
64
cpnode = head .next
65
+
66
+ /* now head is equals cpnode (second node) */
56
67
head = cpnode
57
68
58
69
return head
@@ -62,27 +73,30 @@ func (l *node) popBack() *node {
62
73
if head == nil {
63
74
return head
64
75
}
65
-
76
+ /* create a new node equals to head */
66
77
cpnode := new (node )
67
78
cpnode = head
68
-
79
+
80
+ /* read list to the penultimate node */
69
81
for cpnode .next .next != nil {
70
82
cpnode = cpnode .next
71
83
}
72
-
84
+ /* the penultimate node points to null. In this way the last node is deleted */
73
85
cpnode .next = nil
74
86
return head
75
87
}
76
88
77
89
func main () {
78
90
lista := new (node )
79
- lista .pushBack (25 ).pushBack (24 ).pushBack (32 )
80
- lista .pushBack (56 )
81
- lista .pushFront (36 )
82
- lista .popFront ()
83
- lista .popBack ()
91
+ lista .pushBack (25 ).pushBack (24 ).pushBack (32 ) /* lista: 25 24 32 */
92
+ lista .pushBack (56 ) /* lista: 25 24 32 56 */
93
+ lista .pushFront (36 ) /* lista: 36 25 24 32 56 */
94
+ lista .popFront () /* lista: 25 24 32 56 */
95
+ lista .popBack () /* lista: 25 24 32 */
96
+
97
+ /* read the list until head is not nil */
84
98
for head != nil {
85
99
fmt .Printf ("%d " ,head .v )
86
- head = head .next
100
+ head = head .next /*head points to next node */
87
101
}
88
102
}
0 commit comments