[英]swap last two nodes of singly-linked list
How can I swap the last two nodes of a linked list? 如何交换链表的最后两个节点? I'm trying to use a helper node as I think it's needed to avoid 'losing' a node in the process...
我正在尝试使用一个辅助节点,因为我认为这需要避免在此过程中“丢失”一个节点...
...
Node node3 = new Node("Hi", null) ;
Node node4 = new Node("Hello", null) ;
...
// swap node3 & node4
Node temp = node3.succ ;
node3.succ = null ; // this should be the last node now, so i set its pointer to null
node2.succ = temp ; // the second's node successor becomes what used to be the last node
temp = node4 ; // not sure how to use temp here. what should it point to if at anything?
I think I'm doing this wrong, any hints? 我想我做错了,有什么提示吗?
Suppose you have a linked list A -> B -> C
, and you want to swap B
and C
: 假设您有一个链表
A -> B -> C
,并且想要交换B
和C
:
This looks like a singly-linked list. 这看起来像一个单链表。 You need to make
node4
the successor of node2
(the node whose successor was node3
). 您需要使
node4
成为node2
的后继者(后继者是 node3
的节点)。 You also need to make node3
the successor of node4
. 您还需要使
node3
成为node4
的后继者。 So: 所以:
node2
, node3
, and node4
node2
, node3
和node4
node2.succ
to node4
node2.succ
设置为node4
node4.succ
to node3
node4.succ
设置为node3
node3.succ
to null
node3.succ
设置为null
You could do it more simply/efficiently (though less clearly) if you don't explicitly grab references to all 3 nodes, but that should get you started. 如果您没有显式地获取对所有3个节点的引用,则可以更简单/有效地(尽管不太清楚)来完成此操作,但这应该可以帮助您开始。
You actually have to keep track of three nodes - the last two that you will switch, and one before them, so that you can update it's pointer. 实际上,您必须跟踪三个节点-您将要切换的最后两个节点,以及它们之前的一个节点,以便可以更新其指针。
Alternatively, you can just swap the node values. 或者,您可以只交换节点值。
Well, you've got the right answer already :-) 好吧,您已经有了正确的答案:-)
temp and node4 reference the same object. temp和node4引用相同的对象。 So you've successfully swapped them.
因此,您已经成功交换了它们。 You can now let temp fall out of scope (ie leave it alone).
现在,您可以让温度超出范围(即不理会它)。
So you don't need to set temp to anything. 因此,您无需将temp设置为任何值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.