232. 用栈实现队列

81 阅读1分钟

题目:
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty)

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾 int pop() 从队列的开头移除并返回元素 int peek() 返回队列开头的元素 boolean empty() 如果队列为空,返回 true ;否则,返回 false

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/im… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法:
用数组代替栈,注意数组只能从数组尾部操作

type MyQueue struct {
    Num int
    PushStack []int
    PopStack []int
}


func Constructor() MyQueue {
    return MyQueue{
        Num: 0,
        PushStack: make([]int, 0),
        PopStack: make([]int, 0),
    }
}


func (this *MyQueue) Push(x int)  {
    for i := len(this.PopStack) - 1; i >= 0; i-- {
        this.PushStack = append(this.PushStack, this.PopStack[i])
    }
    this.PopStack = make([]int, 0)
    this.PushStack = append(this.PushStack, x)
    this.Num ++
}


func (this *MyQueue) Pop() int {
    for i := len(this.PushStack) - 1; i >= 0; i-- {
        this.PopStack = append(this.PopStack, this.PushStack[i])
    }
    
    this.PushStack = make([]int, 0)
    ret := this.PopStack[len(this.PopStack) - 1]
    this.PopStack = this.PopStack[:len(this.PopStack) - 1]
    this.Num --
    return ret
}


func (this *MyQueue) Peek() int {
    for i := len(this.PushStack) - 1; i >= 0; i-- {
        this.PopStack = append(this.PopStack, this.PushStack[i])
    }
    return this.PopStack[len(this.PopStack) - 1]
}


func (this *MyQueue) Empty() bool {
    return this.Num == 0
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */