反向链表问题

Reverse Linked List Issue

我正在为学校做一个项目,我的工作是制作一个 LinkedList 程序,用户可以将其读入一行整数并使用 LinkedList 函数反向打印它们。 但是,每次我必须通过按 Ctrl+C 结束从 System.in 读入时,它有点工作。每...次...

我正在尝试找到一种方法来阻止扫描器在读取 int -1 时进行读取。 空格也可以。但是一旦它读到-1,我希望它停止 但是我找不到正确的方法。

这是我目前的情况:

//ReverseUsingLinkedList.java
import java.util.*;
public class ReverseUsingLinkedList
{
    public static void main(String[]args)
    {
        System.out.print("Enter a sequence of Integers, -1 to end: ");

        LinkedList<Integer> num= new LinkedList<Integer>();
        Scanner keyboard = new Scanner(System.in);

        while(keyboard.hasNext())
        {
            num.addFirst(keyboard.nextInt());
        }
        keyboard.close();
        num.removeFirst();       //Removes the -1 from the LinkedList

        System.out.println("List in reverse :" + num.toString());

    }
}

我曾尝试将读取更改为 hasNext.Int(),但这会导致读取跳过我尝试读取的所有其他整数。我也尝试过使用某种迭代器,但找不到正确的使用方法。

有什么建议吗?

测试输入是否为 -1,如果是则中断

while(keyboard.hasNext())
  int num = keyboard.nextInt();
  if (num == -1) // or less than 0 ?
     break;    
  num.addFirst(num);
}

编辑

请注意@nullpointer 非常有效的评论

以 int 形式获取用户输入。将其包含在 try catch 块中。在例外情况下你可以打破。

try{
    int x =keyboard.nextInt();
    if(x==-1)
         break;
catch(Exception e ){
    break;
}
num.addFirst(i);

要使用任何类型的 reader,您需要先遍历 reader 以记录对象的数量,然后再遍历 第二次 使用实际值。尝试以下操作:

int len = 0;

while(keyboard.hasNext())
{
    len++;
}
keyboard.close();

for (int i = 0; i < len; i++)
{
    int temp = keyboard.nextInt();
    if (temp == -1) 
        break;
}

for 循环中退出后,您可以选择是否要删除 -1 元素。 O{n} 将是相同的,除了现在它不会跳转到每个 int 值而不是每个其他值。

此外,我建议您尝试 java.io.BufferedReader 而不是 java.util.Scanner。仅当您将每个 int 都放在单独的行中时才有效,但速度要快 10 倍以上。

虽然@Scary 的回答有助于检查正确的条件。 我建议更新实现以读取下一个输入,并避免在列表中交替输入 --

int input = keyboard.nextInt(); // the first input
while (input !=-1) { // you do not jump with a hasNext() call now
   num.addFirst(input);
   input = keyboard.nextInt(); // successive input
}
// get rid of removeFirst() call

通过上述方法,输入输出就像-

Enter a sequence of Integers, -1 to end: 3
4
5
6
-1
List in reverse :[6, 5, 4, 3]

根据您当前的更新和 Scary 的建议,您可能仍会提供 n 个输入 2, 4, 6, 7, -1 只是为了找到输出 7 , 4 这似乎不是我们想要的。