-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle_linked_list.go
125 lines (104 loc) · 2.37 KB
/
single_linked_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
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
package linkedlist
import (
"fmt"
"strings"
)
// Node 链表的节点
type Node struct {
data interface{}
next *Node
}
// SingleLinkedList 单链表实现
type SingleLinkedList struct {
dummyHead *Node // 链表的虚拟头节点
size int // 链表的长度
}
// NewSll 返回一个空的单链表
func NewSll() *SingleLinkedList {
return &SingleLinkedList{
dummyHead: &Node{},
}
}
func (l *SingleLinkedList) Add(data interface{}) {
l.Insert(0, data)
}
func (l *SingleLinkedList) Append(data interface{}) {
l.Insert(l.size, data)
}
func (l *SingleLinkedList) Insert(pos int, data interface{}) {
if pos < 0 || pos > l.size {
panic("Insert failed, position out of range.")
}
pre := l.dummyHead
for i := 0; i < pos; i++ {
pre = pre.next
}
node := &Node{data: data}
node.next = pre.next
pre.next = node
l.size++
}
func (l *SingleLinkedList) Get(pos int) interface{} {
if pos < 0 || pos >= l.size {
panic("Get failed, position out of range.")
}
cur := l.dummyHead.next
for i := 0; i < pos; i, cur = i+1, cur.next {
}
return cur.data
}
func (l *SingleLinkedList) Remove(pos int) interface{} {
if pos < 0 || pos >= l.size {
panic("Remove failed, position out of range.")
}
pre := l.dummyHead
for i := 0; i < pos; i++ {
pre = pre.next
}
cur := pre.next
pre.next = cur.next
cur.next = nil
l.size--
return cur.data
}
func (l *SingleLinkedList) Delete(data interface{}) {
for pre := l.dummyHead; pre.next != nil; pre = pre.next {
cur := pre.next
if cur.data == data {
pre.next = cur.next
cur.next = nil
l.size--
}
}
}
func (l *SingleLinkedList) Contains(data interface{}) bool {
for cur := l.dummyHead.next; cur != nil; cur = cur.next {
if cur.data == data {
return true
}
}
return false
}
func (l *SingleLinkedList) IsEmpty() bool {
return l.size == 0
}
func (l *SingleLinkedList) Size() int {
return l.size
}
// Values 返回所有节点的值列表
func (l *SingleLinkedList) Values() []interface{} {
values := make([]interface{}, l.size)
for i, cur := 0, l.dummyHead.next; cur != nil; i, cur = i+1, cur.next {
values[i] = cur.data
}
return values
}
func (l *SingleLinkedList) String() string {
var builder strings.Builder
builder.WriteString("Head: ")
for cur := l.dummyHead.next; cur != nil; cur = cur.next {
builder.WriteString(fmt.Sprintf("%v-->", cur.data))
}
builder.WriteString("Null")
return builder.String()
}