转载出处:https://blog.youkuaiyun.com/ctianju/article/details/116744981
问题描述:
用2个栈 , 完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
栈:先进后出,队列:先进先出
/**
* 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
* 栈:先进后出,队列:先进先出
*/
public class StackForQueue {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public static void main(String[] args) {
StackForQueue stackForQueue = new StackForQueue();
stackForQueue.push(5);
stackForQueue.push(2);
stackForQueue.push(3);
stackForQueue.push(4);
stackForQueue.push(5);
System.out.println(stackForQueue.pop());
}
public void push(int num) {
stack1.push(num);
}
public int pop() {
Integer result = null;
if (!stack2.empty()) {
result = stack2.pop();
} else {
while (!stack1.empty()) {
int value = stack1.pop();
stack2.push(value);
}
if (!stack2.empty()) {
result = stack2.pop();
}
}
return result;
}
}