0
点赞
收藏
分享

微信扫一扫

LeetCode-232-用栈实现队列

拾光的Shelly 2021-09-28 阅读 48
LeetCode

用栈实现队列

解法一:双栈实现队列
import java.util.Stack;

public class LeetCode_232 {
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.push(1); // queue is: [1]
        myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
        System.out.println(myQueue.peek() == 1); // return 1
        System.out.println(myQueue.pop() == 1); // return 1, queue is [2]
        System.out.println(myQueue.empty()); // return false
    }
}

class MyQueue {
    private Stack<Integer> inStack;
    private Stack<Integer> outStack;

    /**
     * Initialize your data structure here.
     */
    public MyQueue() {
        inStack = new Stack<>();
        outStack = new Stack<>();
    }

    /**
     * Push element x to the back of queue.
     */
    public void push(int x) {
        inStack.push(x);
    }

    /**
     * Removes the element from in front of queue and returns that element.
     */
    public int pop() {
        if (outStack.isEmpty()) {
            if (inStack.isEmpty()) {
                throw new RuntimeException("stack is empty.");
            } else {
                while (!inStack.isEmpty()) {
                    outStack.push(inStack.pop());
                }
                return outStack.pop();
            }

        } else {
            return outStack.pop();
        }
    }

    /**
     * Get the front element.
     */
    public int peek() {
        if (outStack.isEmpty()) {
            if (inStack.isEmpty()) {
                throw new RuntimeException("stack is empty.");
            } else {
                while (!inStack.isEmpty()) {
                    outStack.push(inStack.pop());
                }
                return outStack.peek();
            }

        } else {
            return outStack.peek();
        }
    }

    /**
     * Returns whether the queue is empty.
     */
    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }

举报

相关推荐

0 条评论