Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java链表。这个程序不打印8。为什么?_Java_Data Structures_Linked List_Singly Linked List - Fatal编程技术网

java链表。这个程序不打印8。为什么?

java链表。这个程序不打印8。为什么?,java,data-structures,linked-list,singly-linked-list,Java,Data Structures,Linked List,Singly Linked List,单链表 我创建节点 添加新节点 实施: //create node class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } public class LinkedList { //Add new node public static void add(Node root, int data){ Node temp; whi

单链表

  • 我创建节点
  • 添加新节点
  • 实施:

    //create node
    class Node {
      int data;
      Node next;
    
      Node(int data) {
        this.data = data;
        next = null;
      }
    }
    public class LinkedList {
    
      //Add new node
      public static void add(Node root, int data){
        Node temp;
        while (root != null) {
          root = root.next;
        }
        temp = new Node(data);
        root = temp;
      }
      //print node
      public static void print(Node root){
        while (root != null) {
          System.out.println(root.data);
          root = root.next;
        }
      }
    
      public static void main(String[] args) {
        Node root ;
        Node iter;
        root = new Node(7);
        iter = root;
        add(iter, 8);
        print(iter);
      }
    
    }
    
    我研究数据结构。我想创建一个链表,但程序失败了。这个程序不打印8。为什么

    我在哪里犯错

    while(root!=null){
       root=root.next;
    }
     temp=new Node(data);
     root=temp;
    
    此处:
    root
    一次为
    NULL
    。 循环之后,不在链的最后一个元素指定下一个元素。您不在链中执行任何操作,因为
    root
    指向
    NULL
    值,并且不引用链中的元素。
    此外,为方法参数赋值没有意义,因为在方法退出时不考虑它

    如果要将节点添加到节点链的末端,应将代码替换为:

    while(root.next !=null){
       root=root.next;
    }
    temp=new Node(data);
    root.next=temp;
    
    你可以用更有意义的名字来写:

    Node lastElement = root;
    while(lastElement.next !=null){
       lastElement=lastElement.next;
    }
    temp=new Node(data);
    lastElement.next=temp;
    
    无论如何,一个更简单的解决方案是在类中有一个字段来存储链的最后一个节点。迭代所有元素以在末尾添加元素不是很有效