【发布时间】:2016-01-07 01:32:52
【问题描述】:
我正在尝试创建一个从输入打印数据结构的程序。输入和输出如下所示:http://puu.sh/kDMc9/2d46462d4d.png。例如,在第一个测试用例中:第一行表示在这种情况下将跟随多少行。那么如果它是数字 1 作为一行中的第一个数字,则表示您要向堆栈/队列/优先队列添加元素,而 2 表示您要取出一个元素,因此一行中的第二个数字是值.然后输出是否是堆栈、队列、优先级队列、不可能或不确定(可以多个)
这是我现在的代码:
import java.util.PriorityQueue;
import java.util.Scanner;
public class DataStructure {
public static void main(String[] args)
{
while(calculate());
}
private static boolean calculate()
{
Scanner input = new Scanner(System.in);
int numberOfRowsPerCase = input.nextInt();
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new Queue<Integer>();
PriorityQueue<Integer> prioQueue = new PriorityQueue<Integer>();
boolean stackBool = true;
boolean queueBool = true;
boolean prioQueueBool = true;
int next;
for(int i = 0; i < numberOfRowsPerCase; i++)
{
next = input.nextInt();
if(next == 1)
{
next = input.nextInt();
stack.push(next);
queue.enqueue(next);
prioQueue.add(next);
}
else if(next == 2)
{
next = input.nextInt();
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
}
if(stackBool == true)
{
System.out.println("stack");
}
else if(queueBool == true)
{
System.out.println("queue");
}
else if(prioQueueBool == true)
{
System.out.println("priority queue");
}
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
else
{
System.out.println("impossible");
}
}
//Check EOF
String in;
in = input.nextLine();
in = input.nextLine();
if(in.equals(""))
{
return false;
}
return true;
}
}
但是当我在上图中运行测试用例时,我的程序会打印出这个:https://ideone.com/mIO1bs 这是错误的。我不知道为什么会这样,这里的其他人可能会看到吗?
【问题讨论】:
标签: java data-structures stack queue