How to implement a single double linked list in Golang
Basic Definition
If you’ve read and read about the Linked List, you can first read Santekno’s post Single Linked List and Double Linked List
In contrast to the previous implementation using C ++ language, now we use the language GO alias rolas usually people say. Actually not too far and complicated to apply it because the script from Golang is easier and concise.
Single Linked List
1package main
2
3type List struct {
4 head *Node
5 tail *Node
6}
7
8func (l *List) First() *Node {
9 return l.head
10}
11
12func (l *List) Push(value int) {
13 node := &Node{value: value}
14 if l.head == nil {
15 l.head = node
16 } else {
17 l.tail.next = node
18 }
19 l.tail = node
20}
21
22type Node struct {
23 value int
24 next *Node
25}
26
27func (n *Node) Next() *Node {
28 return n.next
29}
30
31func main() {
32 l := &List{}
33 l.Push(1)
34 l.Push(2)
35 l.Push(3)
36
37 n := l.First()
38 for {
39 println(n.value)
40 n = n.Next()
41 if n == nil {
42 break
43 }
44 }
45}Single Linked List If we conclude it only has a next () `node. This is a simple example of a single linked list.
Double Linked List
1package main
2
3type List struct {
4 head *Node
5 tail *Node
6}
7
8func (l *List) First() *Node {
9 return l.head
10}
11
12func (l *List) Last() *Node {
13 return l.tail
14}
15
16func (l *List) Push(value int) {
17 node := &Node{value: value}
18 if l.head == nil {
19 l.head = node
20 } else {
21 l.tail.next = node
22 node.prev = l.tail
23 }
24 l.tail = node
25}
26
27type Node struct {
28 value int
29 next *Node
30 prev *Node
31}
32
33func (n *Node) Next() *Node {
34 return n.next
35}
36
37func (n *Node) Prev() *Node {
38 return n.prev
39}
40
41func main() {
42 l := &List{}
43 l.Push(1)
44 l.Push(2)
45 l.Push(3)
46
47 n := l.First()
48 for {
49 println(n.value)
50 n = n.Next()
51 if n == nil {
52 break
53 }
54 }
55
56 n = l.Last()
57 for {
58 println(n.value)
59 n = n.Prev()
60 if n == nil {
61 break
62 }
63 }
64}What distinguishes from single and double linked list? That is, in the Double Linked List the node can know before and after the node being intended. So that we add the `prev () method so that the previous node we know the address of the memory.
Library Go
If you want to learn more related to Linked List can try using the Library Go that has been provided [here] (https://golang.org/pkg/container/list/)
. This is a library that can make it easier for you to implement the Single Linked List or Double Linked List.