我有一個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 –