Quite terse and clean solution yet best in C++


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

  • 0
    I

    Elegant Solution!


Log in to reply
 

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