如何在Java中深度复制双向链表
我在尝试在我的java程序中制作双向链表的深层副本时遇到了相当大的麻烦。
到目前为止我的方法是:
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 是我列表中的第一个 Node,并且这个链表也是循环的。
我的 for 循环出了问题,因为它遍历了列表中的所有元素,然后无限地卡在最后一个元素上。
任何帮助将不胜感激!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的循环结束条件是当前节点之前的节点不是头。我不确定你为什么会有这个,我猜这就是你被卡住的原因。在不知道 Node 类的设计的情况下,我猜测当没有后续节点时,您的
next
成员不会抛出任何类型的迭代异常,因此循环将永远进行(null
节点永远不会与mHead
具有相同的参考值)。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 (anull
Node will never have the same reference value asmHead
).如果我打算复制一个双向链接列表,我只需迭代该列表,复制每个项目,然后将其附加到一个新列表中。计算出插入/追加和迭代函数,然后复制函数就很简单了。
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.
运行当前列表并将每个节点复制到新列表。在下面的列表中,将“theCurrentQueue”替换为您用于存储当前队列的任何内容。
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.