CRCMS

高山仰止,景行行止,虽不能至,心向往之

大道至简


Golang container/list 实现 简单stack

基础实现方法

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
import "container/list"

type Stack struct {
list *list.List
}

func NewStack() *Stack {
return &Stack{
list: list.New(),
}
}

func (s *Stack) Push(value interface{}) {
s.list.PushBack(value)
}

func (s *Stack) Pop() interface{} {
e := s.list.Back()
if e != nil {
s.list.Remove(e)
return e.Value
}

return nil
}

func (s *Stack) Length() int {
return s.list.Len()
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func TestNewStack(t *testing.T) {
stack := NewStack()
stack.Push("a")
stack.Push("b")
stack.Push("c")
stack.Push("d")
assert.Equal(t,4,stack.Length())
v := stack.Pop()
assert.Equal(t,"d",v.(string))
assert.Equal(t,3,stack.Length())
v = stack.Pop()
assert.Equal(t,"c",v.(string))
assert.Equal(t,2,stack.Length())
v = stack.Pop()
assert.Equal(t,"b",v.(string))
assert.Equal(t,1,stack.Length())
v = stack.Pop()
assert.Equal(t,"a",v.(string))
assert.Equal(t,0,stack.Length())
}