首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >java链接列表.This程序不打印8.为什么?

java链接列表.This程序不打印8.为什么?
EN

Stack Overflow用户
提问于 2016-11-27 09:57:15
回答 1查看 139关注 0票数 2

单链接列表。

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

执行情况:

代码语言:javascript
复制
//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.为什么?

我在哪里犯错误?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-27 10:08:25

代码语言:javascript
复制
while(root!=null){
   root=root.next;
}
 temp=new Node(data);
 root=temp;

这里:root一次是NULL。在循环之后,您不会在链的最后一个元素分配下一个元素。您不会在链中执行任何操作,因为root指向一个NULL值,并且不引用链中的一个元素。

此外,它没有意义为一个方法参数赋值,因为当方法退出时,它没有被考虑。

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

代码语言:javascript
复制
while(root.next !=null){
   root=root.next;
}
temp=new Node(data);
root.next=temp;

您可以使用更有意义的名称编写:

代码语言:javascript
复制
Node lastElement = root;
while(lastElement.next !=null){
   lastElement=lastElement.next;
}
temp=new Node(data);
lastElement.next=temp;

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40827659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档