在双链表中插入节点
我无法理解将新节点连接到双链表的后半部分。我正在编写一个 add 方法,该方法接受要在其后插入新节点的节点。我的困难领域是理解在前一个节点链接被重定向到新节点后如何链接到下一个节点。
所以,这就是我
Chunk<E> newChunk= new Chunk<E>();
newChunk.next= prevChunk.next;
prevChunk.next= newChunk;
newChunk.prev= newChunk.next.prev;
newChunk.next.prev= newChunk;
的理解,因为 newChunk.next= prevChunk.next
命令复制了 prevChunk.next 的内存地址并将该值设置为 newChunk.next,然后prevChunk.next 被重置以链接到 newChunk。
因此,由于 prevChunk 是此处引用的唯一已在列表中的节点,并且下一个字段已重新路由到 newChunk,因此我在使用这些引用链接到下一个节点时是否走在正确的轨道上?
I'm having trouble understanding the second half of connecting a new node into a double-linked list. I'm writing an add method that takes in the node which the new node is to be inserted after. My area of difficulty is understanding how to link to the next node after the previous node links have been re-directed to the new node.
So, here's where I've come up with
Chunk<E> newChunk= new Chunk<E>();
newChunk.next= prevChunk.next;
prevChunk.next= newChunk;
newChunk.prev= newChunk.next.prev;
newChunk.next.prev= newChunk;
My understanding is since the newChunk.next= prevChunk.next
command copies the memory address of prevChunk.next and sets that value into newChunk.next, and then the prevChunk.next is reset to link to the newChunk.
So since the prevChunk is the only node referenced here that is already in the list, and the next fields have been re-routed to the newChunk, am I on the right track in using those references to link to the next node?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你是对的,但顺便说一句,大多数双链表不是循环的,因为最后一个节点的下一个不是第一个节点(与第一个节点的前一个不是最后一个节点相同)。
如果“prevChunk”是双链表中的最后一个节点,并且您在 prevChunk 之后添加 newChunk 作为链表中的最后一项,则
本质上是将 NewChunk 的前一个元素设置为 null 的前一个元素,这可能不是您想要的for
您可能想检查 previous.next 最初是否为 null。
You are correct, but on a side note, most double linked lists are not circular, as the lastNode's next isn't the firstNode (same with firstNode's prev is not the lastNode).
If "prevChunk" were the last Node in the double linked list, and you are adding newChunk after prevChunk as the last item in the linked list,
is essentially setting NewChunk's previous element to null's previous element, which probably isn't what you are going for
You might want to check if previous.next initially is null.
像这样的东西应该有效。
Something like this should work.
你那里的东西是正确的。然而,它有点难以理解(因此你的问题)。这是一个更直观的解决方案,应该有效并且更容易理解:
我创建了对链接列表中下一个节点的新引用。这可能与最后一个答案一样有效,因为它创建了新的参考,但应该帮助您理解解决方案。
What you have there is correct. However, it is a bit hard to understand(thus your question). Here is a more intuitive solution that should work and be easier to understand for you:
I create a new reference to the next node in the linked list. This might be be as efficient as the last answer because its creating a new reference but should help you understand the solution.