如何交换链表的最后两个节点?我正在尝试使用辅助节点,因为我认为需要它来避免在此过程中“丢失”节点...
...
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?
我认为我做错了,有什么提示吗?
最佳答案
假设你有一个链表 A -> B -> C
,你想交换 B
和 C
:
- 设置 T* = B(将 B 存储在某处)
- 设置A.next = C
- 设置 T*.next = C.next(这从仅对列表末尾进行操作概括了这一点)
- 设置C.next = T*
关于java - 交换单链表的最后两个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5293222/