Thursday, 20 October 2016

Sort List (LeetCode)

Problem: Sort List
Sort a linked list in O(n log n) time using constant space complexity.

/**
 * 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) {
        mergeSort(&head);
        return head;
    }
    
    void mergeSort(ListNode **head) //pointer of pointer
    {
        ListNode *hd = *head;
        if(hd==NULL || hd->next==NULL) return;
        
        ListNode *a, *b;
        a=*head;
        split(*head, &b);
        mergeSort(&a);
        mergeSort(&b);
        *head = mergeTwo(a, b);
    }
    
    void split(ListNode *head, ListNode **b)
    {
        ListNode *slow, *fast;
        slow = head;
        fast = head->next;
        while(fast!=NULL && fast->next!=NULL)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        *b = slow->next;
        slow->next=NULL;
    }
    ListNode *mergeTwo(ListNode *a, ListNode *b)
    {
        ListNode *head = NULL;
        
        if(a==NULL)
            return b;
        if(b==NULL)
            return a;
            
        if(a->val <= b->val)
        {
            head = a;
            head->next = mergeTwo(a->next, b);
        }
        else 
        {
            head = b;
            head->next = mergeTwo(a, b->next);
        }
        
        return head;
    }
    
};

No comments:

Post a Comment