leetcode题目解答---Insertion Sort List

题目如下:

Sort a linked list using insertion sort.

使用插入排序法排列一个链表。

先来介绍一下插入排序法:

其基本思路就是:

1)分为两个部分,一个部分为已经排序,另一部分为尚未排序。准备三个指针,一个排好序的头指针,一个排好序的尾指针,最后一个为尚未排好序的头指针。

2)每次从未排好序的链表或数组中取出一个数据,插入到排好序的数组或链表中。直到结束。


思路简单,对于链表,主要是插入点的前一个点记得存取,另外一个是每次必须从排好序的头开始遍历,找出要插入的节点位置。

另外,如果插入点是头部,需要特别对待。

代码见下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if (head == NULL || head->next == NULL)
		{
			return head;
		}
		ListNode *sorthead = head;
		ListNode *prepcrsort = head;
		ListNode *pcrsort = sorthead;
		ListNode *sorttail = head;
		ListNode *unsorthead = head;
		ListNode *nextunsort = NULL;
		bool bIsBeginMin = false;
		while (sorttail->next)
		{
			bIsBeginMin = false;
			unsorthead = sorttail->next;
			nextunsort = unsorthead->next;
			if (unsorthead->val < sorttail->val)
			{
				pcrsort = sorthead;
				while (pcrsort != sorttail && pcrsort->val < unsorthead->val)
				{
					bIsBeginMin = true;
					prepcrsort = pcrsort;
					pcrsort = pcrsort->next;
				}
				if (bIsBeginMin)
				{
					prepcrsort->next = unsorthead;
					unsorthead->next = pcrsort;
					sorttail->next = nextunsort;
				}		
				else
				{
					sorthead = unsorthead;
					sorthead->next = pcrsort;
					sorttail->next = nextunsort;
				}
			}
			else
			{
				sorttail = unsorthead;
			}
		}
		return sorthead;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值