从第二个节点获取输出,而不是从第一个节点获取



我要做的是将用户输入作为节点,并将它们添加到链表的前面。然后打印所有元素,但我从第二个节点获得输出,而不是从第一个节点获得。我不确定输入或printList方法出了什么问题。

import java.io.*;
import java.util.*;
public class Solution {
private static Scanner sc = new Scanner(System.in);

Node head;
static class Node{
int data;
Node next;
Node(int d) {
this.data = d;
next = null;
}
}
public void push(int newData){
Node newNode = new Node(newData);
newNode.next = head;
head = newNode;
}
public void printList(){
Node temp = head;
while(temp != null){
System.out.println(temp.data);
temp = temp.next;
}
}
public static void main(String[] args) {
Solution llist = new Solution();
int n = sc.nextInt();
sc.nextLine();
for(int i = 0; i<n; i++){
int input = sc.nextInt();
if(sc.hasNextLine()) llist.push(input);
}
llist.printList();
}
}

输入:

5
383
484
392
975
321

预期输出:

321
975
392
484
383

输出:

975
392
484
383

问题来自main方法中的条件:

public static void main(String[] args) {
Solution llist = new Solution();
int n = sc.nextInt();
sc.nextLine();
for(int i = 0; i<n; i++){
int input = sc.nextInt();
if(sc.hasNextLine()) llist.push(input); // BIG PROBLEM HERE
}
llist.printList();
}

这样做的目的是,只有当扫描仪中仍有行时,它才会执行llist.push(imput);。这意味着您从扫描仪读取的最后一个数字将不会添加到您的llist中。

为了解决你的问题,我认为消除你的if条件就可以了。

最新更新