-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
79 lines (68 loc) · 1.08 KB
/
list.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
package list
type Node[T any] struct {
Value T
Next *Node[T]
}
type List[T any] struct {
head, tail *Node[T]
size uint
zero T
}
func New[T any]() List[T] {
l := List[T]{}
l.head = nil //head指向头部结点
l.tail = nil //tail指向尾部结点
l.size = 0
return l
}
func (l *List[T]) Len() uint {
return l.size
}
func (l *List[T]) Head() *Node[T] {
if l.size == 0 {
return nil
}
return l.head
}
func (l *List[T]) Tail() *Node[T] {
if l.size == 0 {
return nil
}
return l.tail
}
func (l *List[T]) First() (T, bool) {
if l.size == 0 {
return l.zero, false
}
return l.head.Value, true
}
func (l *List[T]) Last() (T, bool) {
if l.size == 0 {
return l.zero, false
}
return l.tail.Value, true
}
func (l *List[T]) Pop() (T, bool) {
if l.size == 0 {
return l.zero, false
}
p := l.head
l.head = p.Next
if l.size == 1 {
l.tail = nil
}
l.size--
return p.Value, true
}
func (l *List[T]) Push(v T) {
node := &Node[T]{v, nil}
if l.size == 0 {
l.head = node
l.tail = node
l.size++
return
}
l.tail.Next = node
l.tail = node
l.size++
}