Short C++ solution with recursion


  • 1
    E
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            ListNode* tail = nullptr;
            return reverse(head, m, n, tail);
        }
        
        ListNode* reverse(ListNode* head, int m, int n, ListNode* &tail) {
            if (m > 1) {
                head->next = reverse(head->next, m - 1, n - 1, tail);
                return head;
            } else if (n > 1) {
                ListNode* node = reverse(head->next, m, n - 1, tail);
                head->next->next = head;
                head->next = tail;
                return node;
            } else {
                tail = head->next;
                return head;
            }
        }
    };

Log in to reply
 

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