您的位置:首页 > 其它

Reverse Linked List II 解答

2015-10-28 22:08 381 查看

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->NULL
, m = 2 and n = 4,

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

Note:
Given m, n 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: