插入排序(Insertion Sort List)

问题:

Sort a linked list using insertion sort.

解析:

由于上一篇已经写了对list的快排和堆排序,所以插入排序很容易上手。直接上代码吧

  ListNode *insertionSortList(ListNode *head) {
        if(head == NULL || head->next == NULL) return head;
    	ListNode *sorthead = head, *insertnode = head->next, *listnext;
    	sorthead->next = NULL;
    	while(insertnode != NULL)
    	{
    		listnext = insertnode->next; //注意保留next
    		if(insertnode->val < sorthead->val) //链表头处理
    		{
    			insertnode->next = sorthead;
    			sorthead = insertnode;
    		}
    		else
    		{
    			ListNode *per= sorthead, *now = per->next;
    			while(now != NULL) //找插入位置
    			{
    				if(now->val >= insertnode->val)
    					break;
    				per = now;
    				now = now->next;
    			}			
    			per->next = insertnode;
    			insertnode->next = now;			
    		}
    		insertnode = listnext;
    	}
        return sorthead;
    }

说明:1.对链表的插入排序比对数组的插入排序效率高~因为不用将原有数据后移来空出位置

           2.对链表头需要特殊处理,思路清晰些很容易,注意初始化sorthead->next = NULL,否则会死循环

嘻嘻~继续加油!!oj~~


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值