Reverse Linked List II 解答

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.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode reverseBetween(ListNode head, int m, int n) {
11         if (m == n || head == null)
12             return head;
13         ListNode dummy = new ListNode(0);
14         dummy.next = head;
15         ListNode pre = dummy, start = dummy, then = dummy, tmp = dummy;
16         // Move pre to (m - 1) position
17         for (int i = 0; i < (m - 1); i++) {
18             pre = pre.next;
19         }
20         // Start = m
21         start = pre.next;
22         then = start.next;
23         start.next = null;
24         // Move (n - m) steps for reverse
25         for (int i = 0; i < (n - m); i++) {
26             tmp = then.next;
27             then.next = start;
28             start = then;
29             then = tmp;
30         }
31         pre.next.next = then;
32         pre.next = start;
33         return dummy.next;        
34     }
35 }

 

posted @ 2015-10-28 22:08  树獭君  阅读(113)  评论(0编辑  收藏  举报