LeetCode题目5:Insertion Sort List

    这个题目要求利用插入排序来排序一个单链表。插入排序的思想就是,长度从1开始,逐步增长已排序的序列长度。具体是:每次从未排序的序列中拿出一个元素,插入到已排序序列的正确位置。这个算法复杂度是O(N^2),在单链表中使用插入排序要比在数组中快一些,因为单链表中省去了元素移动这个步骤。

    这个题目其实也不是那么容易就过的,写的很快也就10分钟,第一版提交后在数据{3,2,4}出现了RE,坑爹的是同样数据我这边编译器运行明明没有异常。后面很小心的改了两处指针边界判断,就过了。感觉这题用前面mergesort之类代码作弊毫无压力。

    P.S. 打算在Git上开一个项目,就叫CrackingLeetCode。估计已经有了类似的?Just for fun。

class Solution {
public:
	ListNode *insertionSortList(ListNode *head) {
		if (head == NULL)
			return head;
		ListNode *newHead = new ListNode(0);
		newHead->next = head;
		ListNode *indexNode = head;
		ListNode *startNode = newHead;
		while (indexNode->next != NULL){
			while (startNode->next != indexNode->next)
			{
				if (startNode->next->val >= indexNode->next->val)
				{
					ListNode* tmp = startNode->next;
					startNode->next = indexNode->next;
					indexNode->next = indexNode->next->next;
					startNode->next->next = tmp;
					break;
				}
				startNode = startNode->next;
			}
			if(startNode->next == indexNode->next)
				indexNode = indexNode->next;
			startNode = newHead;
		}
		return newHead->next;
	}
};


原文地址:https://www.cnblogs.com/xlert/p/3960435.html