Problem
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
1 |
|
Explanation
-
First, we need to know mNode and nNode’s correct position.
-
We need to create one more node that is pointing at the previous of
mNode
calledpreM
. For example, linked list is1->2->3->4->5
,m = 2
n = 4
, sopreM
points at element 1,mNode
points at element 2,nNode
points at element 4. Then, we movemNode
to the next ofnNode
, then updatemNode
to its next element, and repeat this process untilmNode
andnNode
point at the same element. We can illustrate this process below:1
2
31->2->3->4->5 1->3->4->2->5 1->4->3->2->5
Solution
1 |
|