在這一步duplicate.next=new Node(a);
你每次覆蓋以前的值duplicate.next
。當您創建下一個節點時,您應該在每一步更改duplicate
的引用。
你可以使用遞歸來創建下一個節點的副本,之後創建新的節點:
public Node copy() {
Node initial= this;
Node copyNext = this.getNext() == NIL? NIL : this.getNext().copy();
Node duplicate = new Node(initial.getItem());
duplicate.next = copyNext;
return duplicate;
}
和無遞歸:
public Node copy() {
Node currentNode= this;
Node firstDuplicate = new Node(currentNode.getItem()); //save reference for first node to return
Node currentDuplicate=firstDuplicate;
while(Node.NIL!=currentNode.getNext()){
Node nextNode = currentNode.getNext();
Node nextCopy = new Node(nextNode.getItem()); //create copy of next
currentDuplicate.next = nextCopy; //assign this copy as next for current duplicated node
currentDuplicate = nextCopy; //change reference for current duplicated node to copy
currentNode = nextNode;
}
return firstDuplicate;
}
如果我理解你的權利,你需要創建恢復列表。在這種情況下,您不需要創建初始列表的新副本。
public Node reverse() {
Node head = NIL; //initial we have a empty list
Node current = this; //set cursor to current node
while (current != NIL) {
Node copy = new Node(current.getItem()); //create a copy of current node
copy.next = head; //set head node as next for copy
head = copy; //now move head to copy
current = current.next; // move cursor for next position
}
return head;
}
創建遞歸反向列表,你只需要額外的方法,以保持一個參考以前創建的副本:
public Node reverse() {
if (this == NIL) {
return NIL;
}
return reverse(new Node(this.getItem(), NIL), this.getNext());
}
private Node reverse(Node head, Node tail) {
Node copy = new Node(tail.getItem());
copy.next = head;
if (tail.getNext() == NIL) {
return copy;
}
return reverse(copy, tail.next);
}
你是不是能夠正確地更新副本列表,它只會有原始列表的第一個和最後一個節點。 –
我想你是缺少的:duplicate = duplicate.getNext();在循環結束之前。 – alfcope
您需要逐步調試調試器中的代碼,但問題是您只創建一個只有下一個值的節點,即長度必須是兩個。 –