堆栈和链表实现

时间:2014-03-12 02:58:06

标签: java stack queue

我在查询部分遇到问题。

例如,我在堆栈中添加1 2 3 4 5。如果我要查询4,该程序应该删除1 2和3.因此留下4和5.

但我收到了一个错误:

java.util.InputMismatchExceptionat  while(!
(Integer.valueOf(sc.nextInt()).equals(stack.peek())) && !(stack.isEmpty()))

这是我的代码:

public class StackExercise {
   public static void main(String [] args) throws NoSuchElementException {

      StackLL <Integer> stack = new StackLL <Integer> ();
      Scanner sc = new Scanner(System.in);
      String op;

      while (sc.hasNext()) {
         op = sc.next();

         if (op.equals("add")) {
            // Fill in the code 
            while(sc.hasNextInt()){
            stack.push(sc.nextInt());
         }
         sc.nextLine();
         }  else if (op.equals("query"))  {
            // Fill in the code 

            while(sc.hasNextInt()){
               while(!(Integer.valueOf(sc.nextInt()).equals(stack.peek())) && !(stack.isEmpty())){
                  stack.pop();
               }
            }
            sc.nextLine();
          }
         if(op.equals("add")){
            if(stack.isEmpty()){}
            else
               System.out.println("Items added: " +stack.toString());
         }  else if(op.equals("query"))  {
            if(stack.isEmpty())
               System.out.println("Query not met: " +stack.toString());
            else
               System.out.println("Query met: " +stack.toString());
         }
      }
   }
      // You may write additional method(s) to make your program more modular
}

0 个答案:

没有答案