两个队列:
type MyStack struct {
q1 []int
q2 []int
}
func Constructor() MyStack {
return MyStack{
q1: []int{},
q2: []int{},
}
}
func (this *MyStack) Push(x int) {
this.q1 = append(this.q1, x)
}
func (this *MyStack) Pop() int {
for len(this.q1) > 1 {
this.q2 = append(this.q2, this.q1[0])
this.q1 = this.q1[1:]
}
res := this.q1[0]
this.q1 = []int{}
for len(this.q2) > 0 {
this.q1 = append(this.q1, this.q2[0])
if len(this.q2) == 1 {
this.q2 = []int{}
} else {
this.q2 = this.q2[1:]
}
}
return res
}
func (this *MyStack) Top() int {
for len(this.q1) > 1 {
this.q2 = append(this.q2, this.q1[0])
this.q1 = this.q1[1:]
}
res := this.q1[0]
this.q1 = []int{}
for len(this.q2) > 0 {
this.q1 = append(this.q1, this.q2[0])
if len(this.q2) == 1 {
this.q2 = []int{}
} else {
this.q2 = this.q2[1:]
}
}
this.q1 = append(this.q1, res)
return res
}
func (this *MyStack) Empty() bool {
return len(this.q1) == 0
}
/**
* Your MyStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Empty();
*/
一个队列就足够:
type MyStack struct {
queue []int
}
func Constructor() MyStack {
return MyStack{
queue: []int{},
}
}
func (this *MyStack) Push(x int) {
this.queue = append(this.queue, x)
}
func (this *MyStack) Pop() int {
for n := len(this.queue); n > 1; n-- {
val := this.queue[0]
this.queue = this.queue[1:]
this.queue = append(this.queue, val)
}
res := this.queue[0]
this.queue = this.queue[1:]
return res
}
func (this *MyStack) Top() int {
val := this.Pop()
this.queue = append(this.queue, val)
return val
}
func (this *MyStack) Empty() bool {
return len(this.queue) == 0
}
/**
* Your MyStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Empty();
*/