-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoublelist.go
106 lines (90 loc) · 2.07 KB
/
doublelist.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
package orderedmap
import (
"fmt"
"strings"
)
type DoubleList[K, V any] struct {
head *DoubleNode[K, V]
tail *DoubleNode[K, V]
//length int
}
type DoubleNode[K any, V any] struct {
key K
value V
pre *DoubleNode[K, V]
next *DoubleNode[K, V]
//
head bool
tail bool
}
// DoubleListIter to iteration
type DoubleListIter[K, V any] struct {
head *DoubleNode[K, V]
}
func NewDoubleList[K, V any]() ListI[K, V] {
dl := &DoubleList[K, V]{
head: &DoubleNode[K, V]{head: true},
tail: &DoubleNode[K, V]{tail: true},
}
dl.head.next = dl.tail
dl.tail.pre = dl.head
return dl
}
// Insert push back list
func (dl *DoubleList[K, V]) Insert(key K, value V) NodeI[K, V] {
node := &DoubleNode[K, V]{key: key, value: value}
dl.tail.pre.next = node
node.pre = dl.tail.pre
node.next = dl.tail
dl.tail.pre = node
return node
}
// Delete del appoint node
func (dl *DoubleList[K, V]) Delete(nodeI NodeI[K, V]) {
node := nodeI.(*DoubleNode[K, V])
node.pre.next = node.next
node.next.pre = node.pre
}
func (dl *DoubleList[K, V]) Iter() IterI[K, V] {
return &DoubleListIter[K, V]{dl.head}
}
func (dl *DoubleList[K, V]) String() string {
str := &strings.Builder{}
str.WriteString("double linked list:")
head := dl.head.next
for !head.tail {
str.WriteString("[")
str.WriteString(fmt.Sprintf("Key:%v,", head.key))
str.WriteString(fmt.Sprintf("Value:%v", head.value))
str.WriteString("],")
head = head.next
}
return str.String()
}
func (node *DoubleNode[K, V]) GetValue() V {
return node.value
}
func (node *DoubleNode[K, V]) SetValue(value V) {
node.value = value
}
func (node *DoubleNode[K, V]) String() string {
if node == nil {
return "node is nil"
}
str := &strings.Builder{}
str.WriteString("[")
str.WriteString(fmt.Sprintf("Key:%v,", node.key))
str.WriteString(fmt.Sprintf("Value:%v", node.value))
str.WriteString("]")
return str.String()
}
func (iter *DoubleListIter[K, V]) Next() bool {
if iter.head.next.tail {
return false
}
iter.head = iter.head.next
return true
}
func (iter *DoubleListIter[K, V]) KV() (K, V) {
return iter.head.key, iter.head.value
}