leetcode -- Reverse Linked List II

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.

[解题思路]

添加一个safeguard,防止处理m=1的情况,用p1, p2, p3记录m-1, m, n这几个节点的引用

当处理到m+1~n这些节点时将,将它们的next指向前一个节点

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseBetween(ListNode head, int m, int n) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16         if(head == null || m == n){
17             return head;
18         }
19         
20         ListNode fake = new ListNode(Integer.MIN_VALUE);
21         fake.next = head;
22         head = fake;
23         
24         int count = 0;
25         ListNode pre = null, p = head, p1 = null, p2 = null, p3 = null;
26         while(count <= n){
27             if(count == m - 1){
28                 p1 = p;
29             } else if(count == m){
30                 p2 = p;
31             } else if(count == n){
32                 p3 = p;
33             }
34             ListNode tmp = p.next;
35             if(count >= m + 1 && count <= n){
36                 p.next = pre;
37             }
38             pre = p;
39             p = tmp;
40             count++;
41         }
42         p1.next = p3;
43         p2.next = p;
44         return head.next;
45     }
46 }

 

 

posted @ 2013-08-16 20:43  feiling  阅读(246)  评论(0编辑  收藏  举报