开发者

How to make a copy of a doubly linked list?

I'm having real trouble with this; I don't know how to make this code point backwards to the previous node. I can only use get/set Next and Previous. This is what I have so far:

public Doubly copyChildren(){
  Doubly newElement= this.getFirstChild().copyNode();
  Doubly current= th开发者_开发知识库is.getFirstChild();

  while (current.getNext!=null){
    newElement.setNext(current.copyNode());
    current=current.getNext();

  }
  return newElement;
}

can someone help?


I assume you want a deep copy of your doubly linked list.

Doubly iterator = this.getFirstChild();
Doubly newList = iterator.copyNode();
Doubly newListTail = newList;

Doubly deepCurrNode = null
while ((iterator = iterator.getNext()) != null)
{
     deepCurrNode = iterator.copyNode();
     newListTail.setNext(deepCurrNode);
     deepCurrNode.setPrevious(newListTail);
     newListTail = deepCurrNode;
}
//just in case these aren't already null, I'll be explicit
newList.setPrevious(null);
newListTail.setNext(null); 
return newList;

EDIT:

Explanation

the psuedo code is as follows:

while (more items, set iterator equal to next node)
{
   deepCurrNode <-- get deep copy of iterator (this is the item i want to add to my newList)
   Set the tail's next to deepCurrNode to link them
   Set deepCurrNode's previous to the tail to link backwards
   Set the Tail to point to the new tail of the list (deepCurrNode)      

}


You need to iterate inside your list(s) and copy/clone each element into the new list(s).

The problem you are facing is that the LinkedList only keeps internal references to the elements that it contains. When you copy the list a to list b, what you are really doing is copying the references inside list a to list b, so any change on the original list is reflected to the newly copied list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜