有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中生成链表时出现异常

我通过使用for循环逐个扫描链接列表中的元素来添加元素,但在打印列表时,最后出现了0。最后一个节点指向null,但列表中仍有一个元素为0。我在下面提供我的源代码,然后输入

import java.util.Scanner;
import static java.lang.System.out;
class Node{
    int data;
    Node next;
    Node(){
       this.next=null; 
          }
    Node(int data){
        this.data=data;
        this.next=null;
          }
}
public class MyClass{
    public static void main(String args[]) {
        Node head=new Node();
        Node temp=head;
        Scanner sc = new Scanner(System.in);
        int size=sc.nextInt();
        for(int i=1;i<=size;i++){
            temp.data=sc.nextInt();
            temp.next=new Node();
            temp=temp.next;
        }
        temp=null;
        while(head!=null){
            out.print(head.data+" ");
            head=head.next;
        }
    }
  }

投入: 5123445


共 (3) 个答案

  1. # 1 楼答案

    问题是,即使在退出循环后设置temp=null,仍然有一个额外的未分配节点

    最简单的修复方法是删除for循环中的“=”符号,以便在最后一个节点之后退出循环,然后分配最终值,如下所示:

        for(int i=1;i<size;i++){
            temp.data=sc.nextInt();
            temp.next=new Node();
            temp=temp.next;
        }
        temp.data=sc.nextInt();
    
  2. # 2 楼答案

    您将在循环外部创建头部节点,并在其中创建一个新节点
    因此,您将获得1个额外节点

    您可以尝试以下方法:

    public static void main(String args[]) {
        Node head=null;
        Node last=null;
        Scanner sc = new Scanner(System.in);
        int size=sc.nextInt();
        for(int i=1;i<=size;i++){
            if (head == null){
                head = new Node();
                last = head;
            } else {
                last.next = new Node();
                last = last.next();
            }
            last.data=sc.nextInt();
        }
        while(head!=null){
            out.print(head.data+" ");
            head=head.next;
        }
    }
    
  3. # 3 楼答案

    链表最后一个节点中的next指针应为空,以表示它是最后一个节点

    在您的情况下,您将保持它为“NOTNULL”。在for循环中,只要不实例化next指针(如果它是您正在读取的最后一个元素)

        for(int i=1;i<=size;i++){
            temp.data=sc.nextInt();
            if(i != size) {
               temp.next=new Node();
               temp=temp.next;
            }
        }