How to deep copy a Doubly Linked List in Java
I've been having quite a bit of trouble trying to make a deep copy of a doubly linked list in my java program.
My method thus far is:
public class DblLinkQueue implements Queue {
public Object clone() {
DblLinkQueue copy = null;
Node currNode, tmp = null;
try {
copy = (DblLinkQueue)super.clone();
} catch (CloneNotSupportedException err) {}
for (currNode = mHead.next; currNode.next != mHead; currNode = currNode.next) {
}
System.out.println("i: " + i);
return copy;
}
mHead is the first Node in my list, and this linked list is also circular.
Something is wrong with my for loop because it goes through all the elements in the list, then gets stuck on the last element infinitely.
Any help would be appreciated!
Your loop end condition is that the node prior to the current node is not the head. I'm not sure why you have that in there, and I'm guessing that it's why you get stuck. Without knowing the design of your Node class, I'd guess that your next
member doesn't throw any sort of iteration exception when there's no following node, so the loop will go forever (a null
Node will never have the same reference value as mHead
).
If I were intending to copy a doubly-linked list I'd simply iterate through the list, make a copy of each item, and append it to a new list. Work out the insert/append and iterate functions and then the copy function is trivial.
Run the current list and copy each node to a new list. In the list below, replace "theCurrentQueue" with whatever it is that you are using to store the current queue.
public Object clone()
{
Node cloneNode;
DblLinkQueue returnValue = new DblLinkQueue();
for (Node currentNode : theCurrentQueue)
{
cloneNode = currentNode.clone(); // probabaly need to wrap this in a try catch block.
returnValue.add(cloneNode);
}
return returnValue;
}
精彩评论