我有一个HW分配,只有一小部分是制作一个复制构造函数,该构造函数会对您在其参数中输入的链接列表进行深层复制。用于Java中的链接列表的深度复制构造函数
据我所知,这意味着您输入的List
保持不变,并且新链接列表与“旧”链接列表是隔离的。我的代码给了我一个新的列表,它与旧的列表完全相同(您作为参数输入的那个列表),这是我想要的,但旧列表已更改。
这里的构造函数:
public SortedLinkedSet(SortedLinkedSet<T> copy) {
if (copy == null) {
this.firstNode = null;
} else{
SortedLinkedSetNode firstNode1 = new SortedLinkedSetNode(copy.getFirstNode().value);
this.firstNode = firstNode1;
// so basically I am chaining elements from "copy" to firstNode1 and then making "this" = to firstNode1.
while (copy.firstNode.next !=null) {
firstNode1.add(copy.getFirstNode().next.value);
this.firstNode = firstNode1;
copy.firstNode = copy.firstNode.next;
// at the end of this loop I have a successful new linkedList with the same value, but "copy" has been changed
}
}
}
举例来说,如果我进入它具有价值(1,2,3)
链表 - 这个构造我回来与价值1,2,3
一个新的链接列表,但旧的只是有1 ..如果有人能帮助我,为什么这会出错,这将是伟大的。由于
更新:由于Ireeder指出,与测试我做,我几乎可以肯定,这个问题是在声明中: copy.firstNode = copy.firstNode.next; 我删除当前代码,并做了以下测试:
SortedLinkedSetNode firstNode = new SortedLinkedSetNode(copy.getFirstNode().value);
this.firstNode=firstNode;
firstNode.add(copy.getFirstNode().next.value);
this.firstNode = firstNode;
firstNode.add(copy.getFirstNode().next.next.value);
this.firstNode = firstNode;
,这完美的作品(但我事先知道我与只有3个元素列表测试),我会。如何使用while循环做而不使用如下语句: copy.firstNode = copy.firstNode.next; 我必须沿着“复制”列表移动?
这可以帮助你理解这个概念:http://stackoverflow.com/questions/6182565/java-deep-copy-shallow-copy-clone –