LeetCode -- Implement Queue using Stacks

Question:

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

    • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Analysis:

问题描述:请使用栈来实现一个队列。实现其基本功能:push(), pop(), peek(), empty()

注意:只能使用栈的标准功能:push(), peek(), pop(), size(), isEmpty(); 这取决于你使用的语言可能没有可供直接使用的栈,你可以使用链表或双向队列模拟一个栈,只要你仅仅使用栈的标准操作。

思路:使用2个栈模拟一个链表。两次后进先出==先进先出。因此,使用一个栈作为主栈,每次push()操作时直接执行,而当pop()或者peek()时,先依次移到第二个辅助栈中,然后取第二个栈的front指针指向的即可。而判断是否为空时,当且仅当两个栈都为空,队列才为空。

Answer:

class MyQueue {
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        
        // Push element x to the back of queue.
        public void push(int x) {
            s1.push(x);
        }

        // Removes the element from in front of queue.
        public void pop() {
            if(!s2.isEmpty())
                s2.pop();
            else {
                while(!s1.isEmpty()) {
                        int i = s1.peek();
                        s1.pop();
                        s2.push(i);
                }
                s2.pop();
            }
        }

        // Get the front element.
        public int peek() {
            if(!s2.isEmpty())
                    return s2.peek();
            else {
                    while(!s1.isEmpty()) {
                        int i = s1.peek();
                        s1.pop();
                        s2.push(i);
                    }
                    return s2.peek();
            }
        }

        // Return whether the queue is empty.
        public boolean empty() {
            if(s1.isEmpty() && s2.isEmpty())
                    return true;
            return false;
        }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4848509.html