Skip to content

Commit ab64298

Browse files
author
Santo
authored
Comments
1 parent ef2a845 commit ab64298

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

Linkedlist.go

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,43 +2,52 @@ package main
22

33
import "fmt"
44

5+
/* v is the value of node; next is the pointer to next node */
56
type node struct {
67
v int
78
next *node
89
}
910

11+
/* first node, called head. It points from first node to last node */
1012
var head *node = nil
1113

1214
func (l *node) pushFront(val int) *node {
15+
/* if there's no nodes, head points to l (first node) */
1316
if head == nil {
1417
l.v = val
1518
l.next = nil
1619
head = l
1720
return l
1821
} else {
22+
/* create a new node equals to head */
1923
nnode := new(node)
2024
nnode = head
21-
25+
/* create a second node with new value and `next -> nnode`
26+
* is this way, nnode2 is before nnode
27+
*/
2228
nnode2 := &node {
2329
v: val,
2430
next: nnode,
2531
}
32+
/* now head is equals nnode2 */
2633
head = nnode2
2734
return head
2835
}
2936
}
3037

3138
func (l *node) pushBack(val int) *node {
39+
/* if there's no nodes, head points to l (first node) */
3240
if head == nil {
3341
l.v = val
3442
l.next = nil
3543
head = l
3644
return l
3745
} else {
46+
/* read all list to last node */
3847
for l.next != nil {
3948
l = l.next
4049
}
41-
50+
/* allocate a new portion of memory */
4251
l.next = new(node)
4352
l.next.v = val
4453
l.next.next = nil
@@ -50,9 +59,11 @@ func (l *node) popFront() *node {
5059
if head == nil {
5160
return head
5261
}
53-
62+
/* create a new node equals to first node pointed by head */
5463
cpnode := new(node)
5564
cpnode = head.next
65+
66+
/* now head is equals cpnode (second node) */
5667
head = cpnode
5768

5869
return head
@@ -62,27 +73,30 @@ func (l *node) popBack() *node {
6273
if head == nil {
6374
return head
6475
}
65-
76+
/* create a new node equals to head */
6677
cpnode := new(node)
6778
cpnode = head
68-
79+
80+
/* read list to the penultimate node */
6981
for cpnode.next.next != nil {
7082
cpnode = cpnode.next
7183
}
72-
84+
/* the penultimate node points to null. In this way the last node is deleted */
7385
cpnode.next = nil
7486
return head
7587
}
7688

7789
func main() {
7890
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 */
8498
for head != nil {
8599
fmt.Printf("%d ",head.v)
86-
head = head.next
100+
head = head.next /*head points to next node */
87101
}
88102
}

0 commit comments

Comments
 (0)