100170. Implement Queue using Stacks LCCI
2026/1/12大约 1 分钟约 339 字
100170. Implement Queue using Stacks LCCI
难度: Easy
题目描述
Implement a MyQueue class which implements a queue using two stacks.
Example:
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // return 1 queue.pop(); // return 1 queue.empty(); // return false
Notes:
- You must use only standard operations of a stack -- which means only
push to top,peek/pop from top,size, andis emptyoperations 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).
解题思路
代码实现
解决方案
java
class MyQueue {
private Stack<Integer> data;
private Stack<Integer> temp;
private int top=0;
/** Initialize your data structure here. */
public MyQueue() {
data = new Stack<>();
temp = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
if (top == 0) {
top = x;
}
data.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (data.size() == 0) {
return 0;
}
if (data.size() == 1) {
top = 0;
return data.pop();
}
while (data.size() > 1) {
if (data.size() == 2) {
top = data.peek();
}
temp.push(data.pop());
}
int res = data.pop();
while (temp.size() > 0) {
data.push(temp.pop());
}
return res;
}
/** Get the front element. */
public int peek() {
return top;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return data.size()==0;
}
}
/**
* 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();
*/