列表

详情


232. 用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

说明:

 

示例 1:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

 

提示:

 

进阶:

相似题目

用队列实现栈

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class MyQueue { public: MyQueue() { } void push(int x) { } int pop() { } int peek() { } bool empty() { } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */

php 解法, 执行用时: 3 ms, 内存消耗: 20 MB, 提交时间: 2024-03-04 09:36:44

// SplStack 类通过使用一个双向链表来提供栈的主要功能。[PHP 5 >= 5.3.0, PHP 7, PHP 8]
// https://www.php.net/manual/zh/class.splstack.php
class MyQueue {
    // 双栈模拟队列:In栈存储数据;Out栈辅助处理
    private $stackIn;
    private $stackOut;
    
    function __construct() {
        $this->stackIn = new SplStack();
        $this->stackOut = new SplStack();
    }

    // In: 1 2 3  <= push  
    function push($x) {
        $this->stackIn->push($x);
    }

    function pop() {
        $this->peek();
        return $this->stackOut->pop();
    }

    function peek() {
        if($this->stackOut->isEmpty()){
            $this->shift();
        }
        return $this->stackOut->top();
    }

    function empty() {
        return $this->stackOut->isEmpty() && $this->stackIn->isEmpty();
    }

    // 如果Out栈为空,把In栈数据压入Out栈
    // In: 1 2 3 => pop    push => 1 2 3 :Out  
    private function shift(){
        while(!$this->stackIn->isEmpty()){
            $this->stackOut->push($this->stackIn->pop());
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * $obj = MyQueue();
 * $obj->push($x);
 * $ret_2 = $obj->pop();
 * $ret_3 = $obj->peek();
 * $ret_4 = $obj->empty();
 */

java 解法, 执行用时: 0 ms, 内存消耗: 40.4 MB, 提交时间: 2024-03-04 09:31:34

class MyQueue {
    Deque<Integer> inStack;
    Deque<Integer> outStack;

    public MyQueue() {
        inStack = new ArrayDeque<Integer>();
        outStack = new ArrayDeque<Integer>();
    }

    public void push(int x) {
        inStack.push(x);
    }

    public int pop() {
        if (outStack.isEmpty()) {
            in2out();
        }
        return outStack.pop();
    }

    public int peek() {
        if (outStack.isEmpty()) {
            in2out();
        }
        return outStack.peek();
    }

    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }

    private void in2out() {
        while (!inStack.isEmpty()) {
            outStack.push(inStack.pop());
        }
    }
}



/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

cpp 解法, 执行用时: 0 ms, 内存消耗: 8.3 MB, 提交时间: 2024-03-04 09:31:13

class MyQueue {
private:
    stack<int> inStack, outStack;

    void in2out() {
        while (!inStack.empty()) {
            outStack.push(inStack.top());
            inStack.pop();
        }
    }

public:
    MyQueue() {}

    void push(int x) {
        inStack.push(x);
    }

    int pop() {
        if (outStack.empty()) {
            in2out();
        }
        int x = outStack.top();
        outStack.pop();
        return x;
    }

    int peek() {
        if (outStack.empty()) {
            in2out();
        }
        return outStack.top();
    }

    bool empty() {
        return inStack.empty() && outStack.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2021-07-21 10:01:14

type MyQueue struct {
    q []int
    size int
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    return MyQueue{
        []int{},
        0,
    }
}


/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {
    this.q = append(this.q, x)
    this.size++
}


/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
    if this.size == 0 {
        return -1
    }
    temp := this.q[0]
    this.q = this.q[1:this.size]
    this.size--
    return temp
}


/** Get the front element. */
func (this *MyQueue) Peek() int {
    if this.size == 0 {
        return -1
    }
    return this.q[0]
}


/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
    return this.size == 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();
 */

python3 解法, 执行用时: 40 ms, 内存消耗: 12.7 MB, 提交时间: 2019-05-27 13:29:25

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = []
        

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack.append(x)
        

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        temp = self.peek()
        self.stack.remove(temp)
        return temp

    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.stack[0]
        

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return len(self.stack) == 0
        


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

上一题