最好情况:用flag记录上一次是push还是pop,如果和当前操作一致,则直接操作对应的栈,时间复杂度为O(1)。package main
const maxSize = 10
type StackDeque struct {
pushStack *Stack
popStack *Stack
flag bool
}
func (s *StackDeque) exchange(from, to *Stack) {
to.Clean()
for true {
if v, ok := from.Pop(); ok {
to.Push(v)
} else {
break
}
}
s.flag = !s.flag
}
func (s *StackDeque) Push(val int) bool {
if !s.flag {
s.exchange(s.popStack, s.pushStack)
}
return s.pushStack.Push(val)
}
func (s *StackDeque) Pop() (int, bool) {
if s.flag {
s.exchange(s.pushStack, s.popStack)
}
return s.popStack.Pop()
}
type Stack struct {
arr [maxSize]int
size int
}
func (s *Stack) isFull() bool {
if s.size == maxSize {
return true
}
return false
}
func (s *Stack) isEmpty() bool {
if s.size == 0 {
return true
}
return false
}
func (s *Stack) Push(val int) bool {
if s.isFull() {
return false
}
s.arr[s.size] = val
s.size++
return true
}
func (s *Stack) Pop() (int, bool) {
if s.isEmpty() {
return 0, false
}
val := s.arr[s.size-1]
s.size--
return val, true
}
func (s *Stack) Clean() {
s.size = 0
}