leetcode-232-用栈实现队列

Posted 真不知道叫啥好

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-232-用栈实现队列相关的知识,希望对你有一定的参考价值。

题目描述:

 

 

方法一:双栈

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import deque
        self.stack = deque()

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        tmp_stack = []
        while self.stack:
            tmp_stack.append(self.stack.pop())
        self.stack.append(x)
        while tmp_stack:
            self.stack.append(tmp_stack.pop())

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

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

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


# 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()

 java

class CQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    int size;

    public CQueue() {
        stack1 = new Stack<> ();
        stack2 = new Stack<> ();
        size = 0;
    }
    
    public void appendTail(int value) {
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        stack1.push(value);
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        size++;
    }
    
    public int deleteHead() {
        if(size == 0){
            return -1;
        }
        size--;
        return stack1.pop();
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

 

以上是关于leetcode-232-用栈实现队列的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-232-用栈实现队列

leetcode232. 用栈实现队列

leetcode232. 用栈实现队列

leetcode-232-用栈实现队列

leetcode232. 用栈实现队列

精选力扣500题 第27题 LeetCode 232. 用栈实现队列c++ / java 详细题解