将项目添加到链接列表的末尾
问题描述:
我正在为考试而学习,这是旧考试中的一个问题:
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;
}
}