-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
55 lines (45 loc) · 814 Bytes
/
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
package main
import (
"container/list"
"errors"
)
var (
errEmptyStack = errors.New("empty stack")
)
type stack struct {
list *list.List
}
func newStack() *stack {
return &stack{
list: list.New(),
}
}
func (s *stack) Push(value interface{}) error {
s.list.PushBack(value)
return nil
}
func (s *stack) Pop() (interface{}, error) {
e := s.list.Back()
if e != nil {
s.list.Remove(e)
return e.Value, nil
}
return nil, errEmptyStack
}
func (s *stack) IsEmpty() bool {
return s.list.Len() == 0
}
func (s *stack) Size() int {
return s.list.Len()
}
func (s *stack) Peek() (interface{}, error) {
e := s.list.Back()
if e != nil {
return e.Value, nil
}
return nil, errEmptyStack
}
// 这里不暴露底层的 Element 更好。
func (s *stack) Back() *list.Element {
return s.list.Back()
}