-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdouble.go
136 lines (124 loc) · 1.96 KB
/
double.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"fmt"
"strconv"
)
type Content struct {
Id string
}
type Node struct {
Prev *Node
Next *Node
Data *Content
}
type List struct {
N int
First *Node
Last *Node
}
func NewList() *List {
list := new(List)
return list
}
func (l *List) Push(d *Content) *Node {
node := new(Node)
node.Data = d
if l.Last == nil {
l.First = node
l.Last = node
} else {
l.Last.Next = node
node.Prev = l.Last
l.Last = node
}
l.N++
return node
}
func (l *List) Unshift(d *Content) *Node {
node := new(Node)
node.Data = d
if l.First == nil {
l.First = node
l.Last = node
l.N++
} else {
l.First.Prev = node
node.Next = l.First
l.First = node
}
return node
}
func (l *List) Remove(node *Node) *Content {
if node == nil {
return nil
}
if node == l.First && node == l.Last {
l.First = nil
l.Last = nil
} else if node == l.First {
l.First = node.Next
l.First.Prev = nil
} else if node == l.Last {
l.Last = node.Prev
l.Last.Next = nil
} else {
after := node.Next
before := node.Prev
after.Prev = before
before.Next = after
}
l.N--
return node.Data
}
func (l *List) Shift() *Content {
if l.First == nil {
return nil
}
data := l.First.Data
l.Remove(l.First)
return data
}
func (l *List) Pop() *Content {
if l.Last == nil {
return nil
}
data := l.Last.Data
l.Remove(l.Last)
return data
}
func (l *List) Dump() {
if l.First == nil {
fmt.Println("<empty>")
}
p := l.First
i := 1
for p != nil {
fmt.Printf("%02d:%#v[%s]\n", i, p, p.Data.Id)
p = p.Next
i++
}
}
func main() {
var m *Node
d := NewList()
max := 10
for i := 1; i <= max; i++ {
c := new(Content)
c.Id = strconv.Itoa(i)
n := d.Push(c)
if i == max/2 {
m = n
}
}
d.Dump()
fmt.Printf("Pop: %#v\n", d.Pop())
d.Dump()
fmt.Printf("Shift: %#v\n", d.Shift())
d.Dump()
fmt.Printf("Remove: %#v\n", d.Remove(m))
d.Dump()
c := new(Content)
c.Id = strconv.Itoa(max + 1)
fmt.Printf("Unshift: %#v\n", d.Unshift(c))
d.Dump()
}