这是我的代码。它应该将整数放入链表中,直到用户输入-1。它做得很好,但最后它什么都没打印。我不明白为什么整数没有正确存储在列表中。
public static Node read(Scanner scan)
{
int i = scan.nextInt();
Node n = new Node();
if (i == -1)
{
return n;
} else {
n.data = i;
n = n.next;
read(scan);
return n;
}
}
private static void printlist(Node head)
{
if(head == null)
{}
else
{
System.out.print(head.data + " ");
printlist(head.next);
...
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Node head = read(scan);
printlist(head);
}
我按要求添加了main和print方法。我还注意到我在递归读取方法中创建了一个新的Node
。
如何在read方法中声明节点,同时又不创建额外的节点?
答案 0 :(得分:2)
n = n.next
此时n.next的值是多少?为什么要将新节点n设置为此?我的猜测是你的问题就在这里,并且你实际上是在试图设置一个上一个节点"下一个"值到新节点n。听起来不错吗?
答案 1 :(得分:2)
public static Node read(Scanner scan)
{
int i = scan.nextInt();
Node n = new Node();
if (i == -1)
{
return null;
} else {
n.data = i;
n.next=read(scan); //you probably wanted to do this
return n;
}
}