用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
stack1用来压入元素,stack2用来出元素。
stack1中的数字顺序刚好和stack2中顺序是反的,故stack2 的出栈顺序才是出题人想要的到的,当stack2 中还有元素时,此时出元素还是要从stack2 出,仅当stack2 为空,才将stack1元素出栈压入stack2 中,再出元素。
import java.util.Stack;
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.size() <= 0){
while(!stack1.isEmpty()){
int i = stack1.pop();
stack2.push(i);
}
}
return stack2.pop();
}
}