【发布时间】:2014-03-31 00:04:25
【问题描述】:
我有一个链接列表,我正在尝试创建另一个链接列表的副本,这个副本是深层副本,因为元素类型是 char。由于链表的复杂性,我尝试不使用 add 方法。我的代码如下所示。此外,我想递归地将某个列表中的所有元素添加到我的原始列表中,但我的实现的问题是它只添加了列表中的第一个元素,而不是全部。为什么会这样?
public class CharLinkedList {
private static class Node {
private char info;
private Node next;
public Node(char d) {
this.data = d;
this.next = null;
}
}
private int size;
private Node head;
public CharLinkedList() {
this.size = 0;
this.head = null;
}
public CharLinkedList(CharLinkedList some) {
this.size = some.size;
Node node = some.head;
this.head = new Node(other.head.info);
if(node.next != null)
{
this.head.next = new Node(node.next.info);
node = node.next;
this.head.next.next = new Node(node.next.info);
}
}
public void addAll(CharLinkedList some) {
if(some == null){
return;
}
if (this.size == 0) {
Node someNode = new Node(some.get(0));
this.head = someNode;
}
else {
CharLinkedList.addAll(some, this.head.next);
}
this.size++;
}
private static void addAll(CharLinkedList some, Node node) {
if(node.next == null)
{
Node someNode = new Node(some.get(0));
node.next = someNode;
}
else {
CharLinkedList.addAll(some, node.next);
}
}
public static void main(String[] args) {
CharLinkedList l = new CharLinkedList();
l.add('z');
l.add('o');
l.add('m');
CharLinkedList some = new CharLinkedList(l);
some.add('b');
some.add('i');
some.add('e');
System.out.println(l);
System.out.println(some);
// now i change the state of l and append all of some
l.set(1, 'p');
l.addAll(some);
System.out.println(l);
【问题讨论】:
-
为什么不用JCF自带的
LinkedList呢? -
那么......你有没有让这个工作?如果您能接受答案,那将是您的礼貌。