swap last two nodes of singly-linked list

陌路散爱 提交于 2019-12-11 05:36:33

问题


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?


回答1:


Suppose you have a linked list A -> B -> C, and you want to swap B and C:

  1. Set T* = B (store B somewhere)
  2. Set A.next = C
  3. Set T*.next = C.next (this generalizes this from just operating on the end of the list)
  4. Set C.next = T*



回答2:


This looks like a singly-linked list. You need to make node4 the successor of node2 (the node whose successor was node3). You also need to make node3 the successor of node4. So:

  1. Obtain references to node2, node3, and node4
  2. Set node2.succ to node4
  3. Set node4.succ to node3
  4. Set node3.succ to 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.




回答4:


Well, you've got the right answer already :-)

temp and node4 reference the same object. So you've successfully swapped them. You can now let temp fall out of scope (i.e. leave it alone).

So you don't need to set temp to anything.



来源:https://stackoverflow.com/questions/5293222/swap-last-two-nodes-of-singly-linked-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!