LeetCode题解——Sort List

来源:互联网 发布:郑州网络电话软件 编辑:程序博客网 时间:2024/05/22 00:48

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) {} * }; */ /** TLEclass Solution {public:    ListNode* sortList(ListNode* head) {        ListNode* list = head;        while(head!=NULL){            ListNode* p = head;            while(p->next!=NULL){                if(p->val > p->next->val)                {                    int t = p->val;                    p->val = p->next->val;                    p->next->val = t;                }                p = p->next;            }            head = head->next;        }        return list;    }};*/class Solution {public:    ListNode* sortList(ListNode* head) {        if(head == NULL || head->next == NULL) return head;        ListNode* l1= head;        ListNode* l2= head->next;        while(l2!=NULL && l2->next!=NULL)        {            l1 = l1->next;            l2 = l2->next->next;        }        l2 = l1->next;        l1->next = NULL;                return mergeTwoLists(sortList(head),sortList(l2));    }       ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {        if(l1 == NULL) return l2;        if(l2 == NULL) return l1;            if(l1->val < l2->val) {            l1->next = mergeTwoLists(l1->next, l2);            return l1;        } else {            l2->next = mergeTwoLists(l2->next, l1);            return l2;        }    }};

0 0
原创粉丝点击