Monday, November 25, 2013

LeetCode Problem : Reverse Linked List II

Problem


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.

Code

ListNode *rb_r(ListNode *node,int count,int n,
   ListNode **front,ListNode *rear,ListNode **head)
{
if(count == n + 1){
    *front = node;
    return rear;
}
ListNode *prev = rb_r(node->next,count + 1,n,front,rear,head);
    if(!prev){
        *head = node;
    }
    else{
        prev->next = node;
    }
    return node;
}
ListNode *reverseBetween(ListNode *head, int m, int n) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    ListNode *rear = 0;
    ListNode *node = head;
    if(m > 1){
        int count = 1;
        rear = head;
        while(count < m - 1){
            rear = rear->next;
            ++count;
        }
        node = rear->next;
    }
    ListNode *front;
    ListNode *prev = rb_r(node,m,n,&front,rear,&head);
    prev->next = front;
    return head;
}

No comments:

Post a Comment