[leetcode]Sort List

给定一个链表,用O(nlogn)的方法排序...

感觉快排肯定不行了...因为...链表木有办法random access啊..

so用归并排序吧.

感觉链表还挺方便的,挺好写的.

算中间的位置,只有遍历一次了,不过可以用快慢指针找到.

 

然后就是归并了,没啥好多说的...

 

/**
 * 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) return head;
        if(head -> next == NULL){
            return head;
        }
        
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast -> next != NULL && fast -> next -> next != NULL){
            fast = fast -> next;
            fast = fast -> next;
            slow = slow -> next;
        }
        
        ListNode* mid = slow -> next;
        slow -> next = NULL;
        
        ListNode* list1 = sortList(head);
        ListNode* list2 = sortList(mid);
        
        ListNode* sorted = merge(list1 , list2);
        return sorted;
    }
    
    ListNode* merge(ListNode* list1 , ListNode* list2){
        if(list1 == NULL) return list2;
        if(list2 == NULL) return list1;
        
        ListNode* head;
        ListNode* tmp;
        
        if(list1 -> val < list2 -> val){
            head = list1;
            list1 = list1 -> next;
        }else{
            head = list2;
            list2 = list2 -> next;
        }
        tmp = head;
        
        while(list1 != NULL && list2 != NULL){
            if(list1 -> val < list2 -> val){
                tmp -> next = list1;
                tmp = list1;
                list1 = list1 -> next;
            }else{
                tmp -> next = list2;
                tmp = list2;
                list2 = list2 -> next;
            }
        }
        if(list1 != NULL) tmp -> next = list1;
        if(list2 != NULL) tmp -> next = list2;
        
        return head;
    }
};

 

你可能感兴趣的:(LeetCode)