Reverse Linked List II 解答

时间:2023-03-08 19:16:26

Question

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

Solution

Four pointers:

Dummy node, pre, start, then, tmp

First, we find the position to start reversal.

Key point here is to use Dummy node, and pre points the (m - 1) position.

Then, we use three pointers, start, then, tmp to implement reversal. Just the same way as Reverse Linked List.

Several points to note here:

1. Move (m - 1) steps to get pre position

2. Move (n - m) steps to implement reversal

3. Link reversed sub-list with original unreversed sub-lists.

In-place and in one-pass.

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == n || head == null)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy, start = dummy, then = dummy, tmp = dummy;
// Move pre to (m - 1) position
for (int i = 0; i < (m - 1); i++) {
pre = pre.next;
}
// Start = m
start = pre.next;
then = start.next;
start.next = null;
// Move (n - m) steps for reverse
for (int i = 0; i < (n - m); i++) {
tmp = then.next;
then.next = start;
start = then;
then = tmp;
}
pre.next.next = then;
pre.next = start;
return dummy.next;
}
}