本文介绍了将项目添加到链表的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在准备考试,这是旧测试中的一个问题:
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);
但是我怎么能在这里做呢?
But how can I do it here?
推荐答案
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;
}
}
这篇关于将项目添加到链表的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!