C99, 0ms, concise solution with dummy head.

  • 1

    With using dummy head, the boundary condition m == 1 doesn't need any extra consideration.

    struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
        struct ListNode dummy, *l = &dummy;
        l->next = head;
        int i;
        for (i = 1; i < m; i++) l = l->next;
        struct ListNode *r = l->next, *cur;
        for (i = m; i < n; i++) {
            cur = r->next;
            r->next = cur->next;
            cur->next = l->next;
            l->next = cur;
        return dummy.next;

Log in to reply

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