题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:刚开始想的是这样,如果操作是入队的话,那我用A栈先存着,一直到你出队操作时,用B栈pushA栈到达翻转,然后B.pop(),如果还是出队,继续B.pop(),如果入队,将B的再还给A。
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
if(stack1.isEmpty()&&!stack2.isEmpty()){
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
}
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
后来感觉还给A有点多此一举,然后修改了一下程序:
public class Solution3 {
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();
}
}
简单多了