147. 对链表进行插入排序

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;


struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}

};

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if (head == NULL)
            return head;

        ListNode *pre = new ListNode(-1);
        pre->next = head;            // 新链表

        ListNode *tail = head;       // 有序链表(尾插) 
        ListNode *node = head->next; // 遍历无序链表 

        while (node != NULL)
        {
            // 无序第一个节点 小于 有序尾部最后节点(则从头比较) 
            if (node->val < tail->val)
            {
                ListNode *cur = pre->next;   // 遍历有序链表  
                while (cur->next && node->val > cur->next->val)
                {
                    cur = cur->next;
                }
                // 删除 node(无序链表)第一个节点
                tail->next = node->next;
                // 插入新节点 
                node->next = cur->next;
                cur->next = node;

                // 更新无序节点第一个节点 
                node = tail->next;
            }
            else
            {
                tail = tail->next;
                node = tail->next;
            }
        }
        return pre->next;
    }

};

int main()
{
    Solution s;
    ListNode *head = new ListNode(-1), *q = head;
    int data;
    int cnt = 5;
    while (cnt--)
    {
        cin >> data;
        ListNode *p = new ListNode(data);
        q->next = p;
        q = q->next;
    }

    //ListNode *de = head->next;
    //while (de != NULL)
    //{
    //    cout << de->val << " ";
    //    de = de->next;
    //}
    //cout << endl;

    ListNode *res = s.insertionSortList(head);

    while (res != NULL)
    {
        cout << res->val << " ";
        res = res->next;
    }

    cout << endl;
}

 

posted @ 2020-02-23 02:40  douzujun  阅读(136)  评论(0编辑  收藏  举报