将项目添加到链接列表的末尾 [英] Adding items to end of linked list

查看:65
本文介绍了将项目添加到链接列表的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm studying for an exam, and this is a problem from an old test:

我们有一个单链列表,列表头带有以下声明:

We have a singly linked list with a list head with the following declaration:

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

编写方法void addLast(Node header, Object x),将方法x添加到列表的末尾.

Write a method void addLast(Node header, Object x) that adds x at the end of the list.

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

I know that if I actually had something like:

LinkedList someList = new LinkedList();

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

I could just add items to the end by doing:

list.addLast(x);

但是我怎么在这里呢?

推荐答案

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;
   }
}

这篇关于将项目添加到链接列表的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆