reverse linked list between m and n

/* 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. */

struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
};

ListNode *reverse(ListNode *head, int sz) {

       if(sz == 1) return head;
       ListNode *tail;
       if(sz > 1) tail = head;
       ListNode *rlist = nullptr;
       while(sz != 0) {
              ListNode *pre = head;
              head = head->next;
              pre->next = rlist;
              rlist = pre;
              sz--;
       }
       tail->next = head;

       return rlist;
}

ListNode *reverseBetween(ListNode *head, int m, int n) {
       // Start typing your C/C++ solution below
       // DO NOT write int main() function
       int sz = n-m+1;
       if(m == n) return head;

       ListNode *nlist = head;

       if (m == 1)
       {
              nlist = reverse(nlist, sz);
              return nlist;
       } else {
                     ListNode *rhead = head;
                     int index = m-1;
                     while(index > 1) {
                           rhead = rhead->next;
                           index--;
                     }
                     nlist = rhead->next;
                     nlist = reverse(nlist, sz);
                     rhead->next = nlist;
                     return head;
       }
}

void main() {
       ListNode *head = new ListNode(3);
       head->next = new ListNode(5);
//     head->next->next = new ListNode(3);
//     head->next->next->next = new ListNode(4);
//     head->next->next->next->next = new ListNode(5);

       ListNode *nlist = reverseBetween(head, 1, 2);

       while (nlist!=nullptr)
       {
              cout<<nlist->val<<" -> ";
              nlist = nlist->next;
       }

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs