-
Notifications
You must be signed in to change notification settings - Fork 62
/
linked_stack.go
78 lines (64 loc) · 1.19 KB
/
linked_stack.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
package linked_stack
import (
"errors"
"fmt"
)
//链式栈的实现(基于链表)
type ListNode struct {
next *ListNode
val interface{}
}
type LinkedStack struct {
head *ListNode
size int
}
func NewLinkedStack() *LinkedStack {
return &LinkedStack{
head: nil,
size: 0,
}
}
//压栈
func (stack *LinkedStack) Push(val interface{}) {
node := &ListNode{nil, val}
if stack.Empty() {
stack.head = node
} else {
node.next = stack.head
stack.head = node
}
stack.size++
}
//出栈
func (stack *LinkedStack) Pop() (interface{}, error) {
if stack.Empty() {
return nil, errors.New("stack is empty")
}
result := stack.head.val
stack.head = stack.head.next
stack.size--
return result, nil
}
//获取栈顶元素
func (stack *LinkedStack) Peek() (interface{}, error) {
if stack.Empty() {
return nil, errors.New("stack is empty")
}
return stack.head.val, nil
}
func (stack *LinkedStack) Empty() bool {
return stack.size <= 0
}
func (stack *LinkedStack) Size() int {
return stack.size
}
func (stack *LinkedStack) PrintData() {
if stack.Empty() {
fmt.Println("stack is empty")
} else {
for p := stack.head; p != nil; p = p.next {
fmt.Print(p.val, " ")
}
fmt.Println()
}
}