10000 Merge pull request #8 from dcariotti/patch-1 · SelfCodeLearning/Go@eeac937 · GitHub
[go: up one dir, main page]

Skip to content

Commit eeac937

Browse files
Merge pull request TheAlgorithms#8 from dcariotti/patch-1
Added linkedlist
2 parents 9c16bae + ab64298 commit eeac937

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

Linkedlist.go

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

0 commit comments

Comments
 (0)
0