-
题目描述:
-
用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。
-
输入:
-
每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。
-
输出:
-
对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。
-
样例输入:
-
3 PUSH 10 POP POP
-
样例输出:
-
10 -1
源代码如下:
-
package com.lb.test;
import java.util.Scanner;
import java.util.Stack;
public class SimulationQueue {
static Stack<Integer> stack1 = new Stack<Integer>();
static Stack<Integer> stack2 = new Stack<Integer>();
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
int count=0;
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
count = in.nextInt();
do{
String input = in.nextLine();
sb.append(input);
--count;
sb.append("#");
}while(count>=0);
testQueue(sb);
}
private static void testQueue(StringBuffer sb) {
String []instruction = sb.toString().split("\\#");
for(int i = 1;i<instruction.length;++i){
if(instruction[i].contains(" ")){
String [] queueHandle = instruction[i].split(" ");
@SuppressWarnings("unused")
int result = QueueHandle(queueHandle[0],queueHandle[1]);
}else{
int result = QueueHandle(instruction[i],"");
System.out.println(result);
}
}
}
/*
* 两个栈模拟一个队列,首先初始两个栈都为空,当有push操作时,先往stack1中加入一个元素,出队列(pop)的时候依次从stack1中取出
* 元素放入stack2中,然后把栈的第一个元素弹出,然后再把stack2中的元素假如stack1中,并且stack2中元素为空。
*
*/
private static int QueueHandle(String instruction, String value) {
Integer popValue =0;
if(instruction.equals("push")||instruction.equals("PUSH")){
int pushValue = Integer.parseInt(value);
stack1.add(pushValue);
/*
* 执行入队列操作
*/
}else{
/**
* stack1中的所有元素出栈放入stack2中
*/
while(!stack1.empty()){
stack2.add(stack1.pop());
}
/*
* 出队列操作,如果为空,直接返回-1
*/
if(stack2.size()==0){
return -1;
}else{
popValue = stack2.pop();
}
while(!stack2.empty()){
stack1.add(stack2.pop());
}
}
return popValue;
}
}