链表排序(归并法)

来源:互联网 发布:浪潮软件股票分析 编辑:程序博客网 时间:2024/06/03 16:29

1归并法

class ListNode { public:      int val;      ListNode *next;      ListNode(int val) {          this->val = val;          this->next = NULL;      }  }

ListNode *sortList(ListNode *head) {        if (head == nullptr || head->next == nullptr)            return head;        ListNode *mid = findMid(head); //找中点        ListNode *right = sortList(mid->next);        mid->next = nullptr;           //从中间断开        ListNode *left = sortList(head);        return merge(left, right);    }    ListNode* findMid(ListNode* head) {        ListNode *slow = head;        ListNode *fast = head->next;        while (fast && fast->next) {            fast = fast->next->next;            slow = slow->next;        }        return slow;    }    ListNode* merge(ListNode* head1, ListNode* head2) {        ListNode dummy(-1);        ListNode* tail = &dummy;        while (head1 && head2) {            if (head1->val < head2->val) {                tail->next = head1;                head1 = head1->next;            }            else {                tail->next = head2;                head2 = head2->next;            }            tail = tail->next;        }        if (head1) {            tail->next = head1;        }        if (head2) {            tail->next = head2;        }        return dummy.next;    }