Leetcode 148 Solution

This article provides solution to leetcode question 148 (sort-list)

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

Solution

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

        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;

        p2 = sortList(p1);
        p1 = sortList(head);

        ListNode* newhead = NULL;
        ListNode* p = NULL;

        while (p1 && p2)
        {
            ListNode* next_p;

            if (p1->val <= p2->val)
                next_p = p1, p1 = p1->next;
            else
                next_p = p2, p2 = p2->next;

            if (p == NULL)
            {
                p = newhead = next_p;
            }
            else
            {
                p->next = next_p;
                p = next_p;
            }
        }

        if (p1)
            p->next = p1;
        else if (p2)
            p->next = p2;
        else
            p->next = NULL;

        return newhead;
    }
};