92. 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.

---

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
     public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null || head.next == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode cur=dummy;
        int k=m-1;
        while(k>0){
            cur=cur.next;
            k--;
        }
        
        prev=cur;
        cur=cur.next;
        k=n-m;
        while(cur.next!=null && k>0){
            ListNode right =cur.next; // keep the right next
            cur.next=right.next;
            right.next=prev.next;
            prev.next=right;
            k--;
        }
        return dummy.next;
    }
}

 

posted @ 2013-09-21 01:18  LEDYC  阅读(132)  评论(0)    收藏  举报