【问题标题】:java linked list .This program does not print 8.Why?java链表。这个程序不打印 8.为什么?
【发布时间】:2017-04-11 04:37:49
【问题描述】:

单链表。

  1. 我创建节点
  2. 添加新节点

实施:

//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.为什么?

我在哪里犯错了?

【问题讨论】:

    标签: java data-structures linked-list singly-linked-list


    【解决方案1】:
    while(root!=null){
       root=root.next;
    }
     temp=new Node(data);
     root=temp;
    

    这里:root 一次是 NULL。 在循环之后,您不会在链的最后一个元素处分配下一个元素。您不会在链中执行任何操作,因为 root 指向 NULL 值并且不引用链中的元素。
    另外,给方法参数赋值是没有意义的,因为方法退出时没有考虑到它。

    如果要在节点链的末尾添加Node,则应将代码替换为:

    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;
    

    无论如何,一个更简单的解决方案是在你的类中有一个字段来存储链的最后一个节点。遍历所有元素以在末尾添加一个元素效率不高。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      相关资源
      最近更新 更多