leetcode 41: 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->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.

 

 

uncomplete.

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if( m>=n ) return head;
        
        ListNode ** first = &head;
        ListNode* pre = NULL;
        ListNode* cur = head;
        ListNode* nxt;
        while( m-- >1) cur=cur->next;
        
        first = &( cur->next);
        n = n-m+1;
        while( n-- > 0 && cur!=NULL) {
            nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }
        
        (*first)->next = cur;
        
        *first = pre;
        
        return head;
    }
};


 

posted @ 2013-01-16 16:07  西施豆腐渣  阅读(136)  评论(0编辑  收藏  举报