import "errors"
type ArrayStack struct { store []interface{}}
func (s *ArrayStack) Size() int { return len(s.store)}
func (s *ArrayStack) Empty() bool { return len(s.store) == 0}
func (s *ArrayStack) Clear() { s.store = make([]interface{}, 0, 10)}
func (s *ArrayStack) Push(e interface{}) { s.store = append(s.store, e)}
func (s *ArrayStack) Pop() (interface{}, err) { if len(s.store) == 0 { return nil, errors.New("Pop: the stack cannot be empty") } result := s.store[len(s.store)-1] s.store = s.store[:len(s.store)-1] return result, nil}
func (s *ArrayStack) Top() (interface{}, error) { if len(s.store) == 0 { return nil, errors.New("Top: stack cannot be empty") } return s.store[len(s.store)-1], nil}
type LinkedStack struct{ topPtr *node count int}
func (s *LinkedStack) Size() int { return s.count}
func (s *LinkedStack) Empty() bool { return s.count == 0}
func (s *LinkedStack) Clear() { s.count = 0 s.topPtr = nil}
func (s *LinkedStack) Push(e interface{}) { s.topPtr = &node{e, s.topPtr} s.count++}
func (s *LinkedStack) Pop() (interface{}, error) { if s.count == 0 { return nil, errors.New("Pop: the stack cannot be empty") } result := s.topPtr.item s.topPtr = s.topPtr.next s.count-- return result, nil}
func (s *LinkedStack) Top() (interface{}, error) { if s.count == 0 { return nil, errors.New("Pop: the stack cannot be empty") } result s.topPtr.item, nil}
评论