Clean yet efficient solution in C++


  • 3
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) 
        {
            ListNode newHead(0);
            newHead.next = head;
            ListNode *pre = &newHead, *cur = head, *next = NULL;
            int i = 1;
            while(i < n)
            {
                if(i++ < m) { pre = cur; cur = cur->next; }
                else
                { 
                    next = cur->next; 
                    cur->next = cur->next->next; 
                    next->next = pre->next; 
                    pre->next = next; 
                }
            }
            return newHead.next;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.