问题
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:
- Set T* = B (store B somewhere)
- Set A.next = C
- Set T*.next = C.next (this generalizes this from just operating on the end of the list)
- 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:
- Obtain references to
node2,node3, andnode4 - Set
node2.succtonode4 - Set
node4.succtonode3 - Set
node3.succtonull
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