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
mNodecalledpreM. For example, linked list is1->2->3->4->5,m = 2n = 4, sopreMpoints at element 1,mNodepoints at element 2,nNodepoints at element 4. Then, we movemNodeto the next ofnNode, then updatemNodeto its next element, and repeat this process untilmNodeandnNodepoint 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 | |