LeetCode232——用栈实现队列

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/description/

题目描述:

LeetCode232——用栈实现队列

知识点:栈、队列

思路:双栈实现队列

push(x)和empty()的时间复杂度是O(1)。

pop()和peek()的时间复杂度是O(n),其中n为队列中的元素个数。

JAVA代码:

public class MyQueue {
	private Stack<Integer> stack1;
	private Stack<Integer> stack2;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
    	while(!stack1.isEmpty()) {
    		stack2.push(stack1.pop());
    	}
    	int result = stack2.pop();
    	while(!stack2.isEmpty()) {
    		stack1.push(stack2.pop());
    	}
    	return result;
    }
    /** Get the front element. */
    public int peek() {
    	while(!stack1.isEmpty()) {
    		stack2.push(stack1.pop());
    	}
    	int result = stack2.peek();
    	while(!stack2.isEmpty()) {
    		stack1.push(stack2.pop());
    	}
        return result;
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}

LeetCode解题报告:

LeetCode232——用栈实现队列