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

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(m==n||m>n)
            return head;
        int len = n-m;
        ListNode root = head;
        m--;
        while(m!=0&&root!=null){
            root = root.next;
            m--;
        }
        ListNode cur = root;
        while(len!=0&&len>0){
            ListNode temp = cur;
            int i=len;
            while(i!=0){
                temp=temp.next;
                i--;
            }
                
            int tempv = cur.val;
            cur.val=temp.val;
            temp.val=tempv;
            len-=2;
            cur=cur.next;
        }
        
        return head;
        
    }
}

 

posted @ 2014-05-11 15:05  一弦一仙  阅读(105)  评论(0编辑  收藏  举报