Sort List

来源:互联网 发布:淘宝联盟导购推广名称 编辑:程序博客网 时间:2024/05/16 12:03

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

思路:因为要用O(nlogn)的时间复杂度,用归并排序比较简单快捷。code是参考某大神的。:)

class Solution {public:    ListNode *sortList(ListNode *head) {        if (head == NULL || head->next == NULL) {            return head;        }                ListNode *slow = head;        ListNode *fast = head;        ListNode *tail = head;                while (fast != NULL && fast->next != NULL) {            fast = fast->next->next;            tail = slow;            slow = slow->next;        }                tail->next = NULL;                ListNode *first = sortList(head);        ListNode *second = sortList(slow);                head = new ListNode(0);        tail = head;                while (first != NULL & second != NULL) {            if (first->val <= second->val) {                tail->next = first;                first = first->next;            }            else {                tail->next = second;                second = second->next;            }                        tail = tail->next;        }                if (first != NULL) {            tail->next = first;        }                if (second != NULL) {            tail->next = second;        }                tail = head->next;        delete head;        return tail;    }};


0 0
原创粉丝点击