简体   繁体   English

交换单链列表的最后两个节点

[英]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 ,并且想要交换BC

  1. Set T* = B (store B somewhere) 设置T * = B(将B存储在某个地方)
  2. Set A.next = C 设置A.next = C
  3. Set T*.next = C.next (this generalizes this from just operating on the end of the list) 设置T * .next = C.next(这可以从仅在列表末尾进行操作来概括)
  4. Set C.next = T* 设置C.next = T *

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: 所以:

  1. Obtain references to node2 , node3 , and node4 获取对node2node3node4
  2. Set node2.succ to node4 node2.succ设置为node4
  3. Set node4.succ to node3 node4.succ设置为node3
  4. Set 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM