225.用队列实现栈
代码:
type MyStack struct {
queueA []int
queueB []int
}
func Constructor() MyStack {
return MyStack{}
}
func (this *MyStack) Push(x int) {
this.queueB = append(this.queueB,x)
this.queueB = append(this.queueB,this.queueA...)
this.queueA =this.queueB
this.queueB = []int{}
}
func (this *MyStack) Pop() int {
ret := this.queueA[0]
this.queueA = this.queueA[1:len(this.queueA)]
return ret
}
func (this *MyStack) Top() int {
return this.queueA[0]
}
func (this *MyStack) Empty() bool {
if len(this.queueA) == 0{
return true
}
return false
}
思路:
- push进来的时候保证一个队列中的顺序是栈的存储顺序
- 每次Push一个元素进来时,放到一个新的队列中
- 然后将旧的队列元素push到其后面就实现了,队列中的顺序是新->旧的顺序。
- 然后放回A队列