1. 程式人生 > >147 連結串列插入排序

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;
}