Leetcode 143 Solution

This article provides solution to leetcode question 143 (reorder-list)

https://leetcode.com/problems/reorder-list

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if (head == NULL || head->next == NULL)
            return;

        ListNode* prev = NULL;
        ListNode* p1 = head;
        ListNode* p2 = head;

        while (p1 && p2)
        {
            prev = p1;
            p1 = p1->next;
            p2 = p2->next;

            if (p2)
                p2 = p2->next;
        }

        prev->next = NULL;
        prev = NULL;

        while (p1)
        {
            ListNode* next = p1->next;
            p1->next = prev;

            prev = p1;
            p1 = next;
        }

        p1 = head;
        p2 = prev;

        while (p2)
        {
            ListNode* next1 = p1->next;
            ListNode* next2 = p2->next;

            p2->next = p1->next;
            p1->next = p2;

            p1 = next1;
            p2 = next2;
        }
    }
};