题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
首先必须明白栈和队列的区别。stack1只需要不断地往里push,stack2最上面的元素就是原来stack1最底下的元素。当stack2为空的时候才需要把stack1的元素压到stack1中。
直接上代码:
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
参考:
https://cyc2018.github.io/CS-Notes/#/notes/剑指 Offer 题解 - 3~9?id=_9-用两个栈实现队列