147 链表插入排序

ListNode *insertionSortList(ListNode *head) {
    if (head == nullptr || head->next == nullptr)
        return head;
    auto *prehead = new ListNode(0), *front = prehead;
    prehead->next = head;
    ListNode *it = head->next;
    head->next = nullptr;
    while (it != nullptr) {
        front = prehead;
        while (front->next != nullptr && front->next->val < it->val)
            front = front->next;
        if (front->next == nullptr) {
            front->next = it;
            it = it->next;
            front->next->next = nullptr;
        } else {
            ListNode *temp = it->next;
            it->next = front->next;
            front->next = it;
            it = temp;
        }
    }
    return prehead->next;
}
posted @ 2019-01-12 17:40  INnoVation-V2  阅读(104)  评论(0编辑  收藏  举报