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.

class Solution {
public:
    void reverse(ListNode *& head,ListNode *& end){
        ListNode *h = head,*e = end;
        if (h->next == e){
            e->next = h;
            h->next = NULL;
            end = h;
            head = e;
            return;
        }
        ListNode * p = h->next;
        reverse(p,e);
        e->next = h;
        h->next = NULL;
        head = p;
        end = h;
        return;     
    }
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int i = 1;
        if (m >= n){
            return head;
        }
        ListNode * s = NULL, *e = NULL, *s1 = NULL, *e1 = NULL;
        ListNode * h = head;
        for(ListNode *p = head; p; p = p->next){
            if (i + 1 == m){
                s1 = p;
            }else if (i == m){
                s = p;
            }else if (i == n){
                e = p;
                e1 = p->next;
                if (s && e){
                    reverse(s,e);
                    if (s1){
                        s1->next = s;
                    }
                    if (m == 1){
                        h = s;
                    }
                    e->next = e1;
                    break;
                }
            }
            i++;
        }
        return h;
    }
};

 

posted @ 2013-07-09 21:47  一只会思考的猪  阅读(165)  评论(0编辑  收藏  举报