题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
- 用两个栈实现一个队列,完成队列的Push和Pop操作;
- 队列中的元素为int类型;
- 栈stack1作为用来作入队列,栈stack2用来出队列;
- 当栈stack1和栈stack2全为空时,抛出异常;
- 当栈stack2为空时,栈stack1全部出栈到栈stack2,栈stack2再出栈(即出队列)。
程序:
import java.util.Stack;
public class subject5 {
public static void main(String args[]){
subject5 sub = new subject5();
sub.push(1);
sub.push(2);
sub.push(3);
System.out.print(sub.pop());
}
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node){
stack1.push(node);
}
public int pop(){
if(stack1.isEmpty() && stack2.isEmpty()){
throw new RuntimeException("队列不能为空");
}
if(stack2.isEmpty()){
while(! stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}