1.题目描述:
2.解法:(关键在于使用两个栈进行模拟)
class MyQueue {
Stack stackIn = new Stack<>();//入栈 *** 作
Stack stackOut = new Stack<>();//出栈 *** 作
public MyQueue() {
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
reverse();
return stackOut.pop();
}
public int peek() {
reverse();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void reverse() {
if (!stackOut.isEmpty()) return;
//一旦涉及pop、push就会调用;但是一旦出栈的栈中有元素,
//则不把入栈的元素放入(否则破环队列的先进先出),直到出栈的元素为空再入
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
/**
* 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();
*/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)