将项目添加到链表的末尾

新手上路,请多包涵

我正在为考试而学习,这是一个旧考试的问题:

我们有一个单链表,其表头具有以下声明:

 class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d;
        next = n;
    }
}

编写一个方法 void addLast(Node header, Object x) --- 在列表末尾添加 x

我知道,如果我真的有类似的东西:

 LinkedList someList = new LinkedList();

我可以通过执行以下操作将项目添加到末尾:

 list.addLast(x);

但是我怎么能在这里做到呢?

原文由 John 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 476
2 个回答
class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d ;
        next = n ;
       }

   public static Node addLast(Node header, Object x) {
       // save the reference to the header so we can return it.
       Node ret = header;

       // check base case, header is null.
       if (header == null) {
           return new Node(x, null);
       }

       // loop until we find the end of the list
       while ((header.next != null)) {
           header = header.next;
       }

       // set the new node to the Object x, next will be null.
       header.next = new Node(x, null);
       return ret;
   }
}

原文由 therin 发布,翻译遵循 CC BY-SA 2.5 许可协议

您想要使用循环浏览整个链表并检查每个节点的“下一个”值。最后一个节点将是下一个值为 null 的节点。只需将该节点的下一个值设为您使用输入数据创建的新节点。

 node temp = first; // starts with the first node.

    while (temp.next != null)
    {
       temp = temp.next;
    }

temp.next = new Node(header, x);

这是基本的想法。这当然是伪代码,但实现起来应该足够简单。

原文由 Benjamin S 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题