用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
分析:
栈Stack 自带的方法:
public E pop()移除栈顶部的对象,并作为此函数的值返回该对象。
public E push(E item)插入到栈顶部
代码如下:
import java.util.Stack;
/*
* 一个队列弹出,然后另一个队列压入
*/
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//压入,push方法
public void insert(int node) {
stack1.push(node);
}
//弹出
public int delete() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public static void main(String[] args) {
Solution s = new Solution();
s.insert(2);
s.insert(3);
s.insert(4);
s.delete();
}
}