链表的插入排序

首先介绍一下直接插入排序,对于无序序列2,4 ,3,1,5。首先初始化两个序列,有序序列{2}和无序序列{4,3,1,5},把4放进有序序列,从第一个节点开始比较,找到插入位置,把带插入节点插入相应的位置,得到新的序列{2,4},{3,1,5},依次进行下去,直至无序序列为空。

下面来介绍链表的插入排序

(1)初始化带头节点L有序链表,ListNode *L=new ListNode(-1);ListNode *pre=head;L->next=pre;pre->next=NULL;

(2)无序链表,ListNode *cur=head->next;

(3)ListNode *front:记录插入位置,ListNode *in:记录带插入节点

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        ListNode *L=new ListNode(-1);
        ListNode *pre=L;      //有序链表指针
        ListNode *in;         //待插入节点
        ListNode *front;      //节点插入位置
        pre->next=NULL;
        if(head==NULL) return L->next;
        ListNode *cur=head;                   //无序链表指针
        pre->next=head;
        cur=cur->next;         //无序从第二个节点开始
        pre->next->next=NULL;      //有序保存一个节点
        while(cur)
        {
            in=cur;
            pre=L->next;       //从第一个节点开始比较
            while(pre&&pre->val<in->val)
            {
                front=pre;                         //当前可插入位置
                pre=pre->next;
            }
            cur=cur->next;
            if(pre==L->next) L->next=in;        //比第一个节点小,头结点为带插入节点
            else front->next=in;                 //待插节点放在插入位置后
            in->next=pre;
        }
        return L->next;
    }
};

猜你喜欢

转载自blog.csdn.net/baidu_38812770/article/details/81197659