2011-03-13 38 views
1

如何交换链表的最后两个节点?我试图使用一个辅助节点,因为我认为这是需要避免的过程中“丢失”的一个节点......交换单链表的最后两个节点

... 
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? 

我觉得我这样做不对,任何提示?

回答

4

假设你有一个链表A -> B -> C,并且要交换BC

  1. 集T * = B(存储器B某处)
  2. 设置A.next = C
  3. 套装T *的.next = C.next(此概括这从刚刚在列表的末尾操作)
  4. 集C.next = T *
+0

非常感谢你! – raoulbia

1

这看起来像是单链表。您需要让node4继承node2(节点的后继node3)。您还需要使node3继承node4。所以:

  1. 获取引用node2node3,并node4
  2. 设置node2.succnode4
  3. 设置node4.succnode3
  4. 设置node3.succnull

你可以做到这一点更简单/如果你没有明确地抓住,那么有效(尽管不太清楚)引用所有3个节点,但这应该让你开始。

0

您实际上必须跟踪三个节点 - 您将切换的最后两个节点,以及一个前面的节点,以便您可以更新它的指针。

或者,您可以交换节点值。

1

好,你已经得到了正确的答案:-)

温度和节点4引用同一个对象。所以你已经成功交换了它们。你现在可以让温度超出范围(即保持不变)。

所以你不需要设置任何东西的温度。

相关问题