首页 > 其他 > 详细

Reverse Linked List II 解答

时间:2015-10-28 23:01:22      阅读:340      评论:0      收藏:0      [点我收藏+]

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 }

 

Reverse Linked List II 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4918863.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!