20ms 8lines c++ solution, easy to understand

  • 0

    The idea is we maintain two heads of two lists, the odd list and the even list. Then we scan the whole list, append odd elements to odd list, and append even elements to even list. At last we connect the two lists.
    And we can use some techniques to make our code simpler:

    ListNode* oddEvenList(ListNode* head) {
        ListNode *odd_head = new ListNode(0), *even_head = new ListNode(0);
        ListNode * two_lists[2] = { odd_head, even_head };
        for (int i = 0; head; head = head->next, i = 1 - i) {
            two_lists[i] = two_lists[i]->next = head;
        two_lists[0]->next = even_head->next;
        two_lists[1]->next = NULL;
        return odd_head->next;

Log in to reply

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