-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathstack_list.go
More file actions
54 lines (45 loc) · 883 Bytes
/
stack_list.go
File metadata and controls
54 lines (45 loc) · 883 Bytes
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
package stack
import "errors"
//使用链表实现栈
//以下是使用单向链表,使用头插法实现,也可以使用标准库的双向链表实现
//节点,需要动态申请内存空间
type Node struct {
data int
next *Node
}
//栈
type ListStack struct {
top *Node
}
func NewListStack() *ListStack {
return &ListStack{}
}
//是否为空
func (ls *ListStack) IsEmpty() bool {
return ls.top == nil
}
//入栈,头插法
func (ls *ListStack) Push(i int) {
//新建节点
n := &Node{i, nil}
if ls.top != nil {
n.next = ls.top
}
ls.top = n
}
//出栈,从头弹出
func (ls *ListStack) Pop() (int, error) {
if ls.top == nil {
return 0, errors.New("栈空")
}
i := ls.top.data
ls.top = ls.top.next
return i, nil
}
//查看
func (ls *ListStack) Peek() (int, error) {
if ls.top == nil {
return 0, errors.New("栈空")
}
return ls.top.data, nil
}