Leetcode 147 Solution

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

https://leetcode.com/problems/insertion-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* insertionSortList(ListNode* head) {
        ListNode dummynode(INT_MIN);
        dummynode.next = head;

        ListNode* p = head;
        ListNode* pprev = &dummynode;

        while (p)
        {
            ListNode* next = p->next;

            ListNode* q = dummynode.next;
            ListNode* qprev = &dummynode;

            while (q != p && q->val <= p->val)
            {
                qprev = q;
                q = q->next;
            }

            if (q != p)
            {
                pprev->next = p->next;
                qprev->next = p;
                p->next = q;

                p = next;
            }
            else
            {
                pprev = p;
                p = next;
            }
        }

        return dummynode.next;
    }
};