代码
stack.go
package stack
//defined a element struct
type Element struct {
value interface{}
prev *Element
}
// Prev get the prev element
func (e *Element) Prev() *Element {
if p := e.prev; p != nil {
return p
}
return nil
}
func (e *Element) Value() interface{} {
return e.value
}
// defined an stack
type Stack struct {
top *Element
len int
}
// init the stack
func (s *Stack) Init() *Stack {
s.top = nil
s.len = 0
return s
}
func New() *Stack {
return new(Stack).Init()
}
func (s *Stack) Pop() *Element {
if s.Len() == 0 {
return nil
}
t := s.top
s.top = t.prev
s.len--
return t
}
func (s *Stack) Push(e *Element) {
e.prev = s.top
s.top = e
s.len++
}
func (s *Stack) Peek() *Element {
return s.top
}
func (s *Stack) Len() int {
return s.len
}
测试
stack_test.go
package stack
import (
"math/rand"
"testing"
"time"
)
var answer = []string{
"php",
"go",
"c++",
"js",
"java",
"dd",
"css",
"html",
}
func BenchmarkStack_Push(b *testing.B) {
l := len(answer)
s := New()
b.ResetTimer()
for i := 0; i < b.N; i++ {
rand.Seed(time.Now().UnixNano())
r := rand.Intn(l)
s.Push(&Element{value: answer[r]})
}
}
func BenchmarkStack_Pop(b *testing.B) {
l := len(answer)
s := New()
for i := 0; i < 100000; i++ {
rand.Seed(time.Now().UnixNano())
r := rand.Intn(l)
s.Push(&Element{value: answer[r]})
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
s.Pop()
}
}
func TestStack_Push(t *testing.T) {
s := New()
for _, e := range answer {
s.Push(&Element{value: e})
}
//s.Pop()
top := s.Peek()
v := top.Value()
// type assertion
a, ok := v.(string)
if !ok {
t.Error("type assertion error")
}
if a != "html" {
t.Error("expected html, actual", a)
}
}