Leetcode 328 Solution

This article provides solution to leetcode question 328 (odd-even-linked-list)

https://leetcode.com/problems/odd-even-linked-list

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        ListNode oddhead(0);
        ListNode evenhead(0);
        ListNode* odd_prev = &oddhead;
        ListNode* even_prev = &evenhead;
        auto p = head;

        while (p)
        {
            odd_prev->next = p;
            odd_prev = p;
            p = p->next;

            if (p == NULL)
                break;

            even_prev->next = p;
            even_prev = p;
            p = p->next;
        }

        odd_prev->next = evenhead.next;
        even_prev->next = NULL;
        return oddhead.next;
    }
};