LeetCode Insertion Sort List 最新题解

Insertion Sort List 

Sort a linked list using insertion sort.

题目很短,注意:画图,解决边界,特殊情况。插入指针的时候要注意保存原来node的next,这个很容易出错。

一定要优先考虑到头指针和尾指针和空指针的情况。

下面给出完整程序了:

#include<iostream>
#include<vector>
#include<algorithm>

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) return nullptr;
		ListNode *newH = new ListNode(head->val);
		ListNode *headTemp = head->next;

		while (headTemp)
		{			
			insertNode(newH, headTemp);
		}
		return newH;
	}

	ListNode *findListPos(ListNode *(&h), ListNode *(&node))
	{
		ListNode *htemp = h;
		while (htemp->next && htemp->next->val <= node->val)
		{
			htemp = htemp->next;
		}
		return htemp;
	}

	void insertNode(ListNode *(&h),ListNode *(&node))
	{
		if(!node) return;
		if (!h || node->val < h->val)
		{
			//注意:那里都要注意保存->next的值之后再插入
			ListNode *nodeNext = node->next;
			node->next = h;
			h = node;
			node = nodeNext;
			return;
		}
		//注意这里的插入操作,很麻烦,一定要熟悉!!!
		ListNode *htemp = findListPos(h, node);
		ListNode *saveNode = htemp->next;
		ListNode *nodeNext = node->next;
		htemp->next = node;
		node->next = saveNode;
		node = nodeNext;
	}
};

int main()
{
	ListNode t1(3);
	ListNode t2(4);
	ListNode t3(1);
	t1.next = &t2;
	t2.next = &t3;
	ListNode *h = &t1;
	while (h)
	{
		cout<<h->val<<" ";
		h = h->next;
	}
	cout<<endl;
	Solution solu;
	h = &t1;
	h = solu.insertionSortList(h);
	while (h)
	{
		cout<<h->val<<" ";
		h = h->next;
	}
	cout<<endl;

	system("pause");
	return 0;
}


可以由上面的一大坨代码简化成这样:

//2014-2-19 update
	ListNode *insertionSortList(ListNode *head) 
	{
		ListNode dummy(INT_MIN);//dummy.next = head;无需这句
		while (head)
		{
			ListNode *p = &dummy;
			for ( ;p->next && head->val >= p->next->val; p = p->next);
			ListNode *t = head;
			head = head->next;
			t->next = p->next;
			p->next = t;
		}
		return dummy.next;
	}




 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值