My concise c++ codes, 8ms


  • 0
    K

    Move to the m element firstly, and then move elements in (m, n] to the front of m one by one.

    class Solution {
    public:
        ListNode *reverseBetween(ListNode *head, int m, int n) {
            ListNode *prev = NULL;
            ListNode *tail = head;
            int move = m - 1;
            while (move-- > 0) {
                prev = tail; tail = tail->next;
            }
            
            int num = n - m;
            ListNode *front = tail;
            while (num-- > 0) {
                ListNode *tmp = tail->next;
                tail->next = tmp->next;
                tmp->next = front;
                front = tmp;
                if (prev) prev->next = front;
            }
            return prev ? head : front;
        }
    };

Log in to reply
 

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