Leetcode 147. Insertion Sort List(链表实现快排)

147. Insertion Sort List

Total Accepted: 66609 Total Submissions: 230331 Difficulty: Medium

Sort a linked list using insertion sort.

Subscribe to see which companies asked this question

Have you met this question in a real interview?


链接: https://leetcode.com/problems/insertion-sort-list/


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>

typedef long long ll;
#define eps 1e-8

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hi"\n)
using namespace std;
#define INF 0x3f3f3f3f
#define N 30

struct ListNode{
	int val;
	ListNode *next;
	ListNode(int x):val(x),next(NULL){

	}
};

void show(ListNode * head)
{
	while(head)
	{
		printf("%d ",head->val);
		head=head->next;
	}
	printf("\n");
}

class Solution{
	public:
		ListNode *insertionSortList(ListNode * head)
		{
			if(head==NULL||head->next==NULL) return head;
			ListNode* pre=new ListNode(0);
			quicksort(pre,head,NULL);
			head=pre->next;
			delete pre;
			return head;
		}
		ListNode * quicksort(ListNode* pre,ListNode * head,ListNode *tail)
		{
			if(head==tail) return head;
			if(head->next==NULL) return head;
			ListNode * mid=getpos(pre,head,tail);
			quicksort(pre,pre->next,mid);
			quicksort(mid,mid->next,tail);
			return pre;
		}
		ListNode * getpos(ListNode* pre,ListNode *head,ListNode * tail)
		{
			ListNode *small=new ListNode(0),*big=new ListNode(0);
			ListNode *ss=small,*bb=big;
			for(ListNode * it=head->next;it!=tail;it=it->next)
				if(it->val<=head->val)
				{
					small->next=it;
					small=it;
				}
			   else
			   {
				   big->next=it;
				   big=it;
			   }
			big->next=tail;
			head->next=bb->next;
			small->next=head;
			pre->next=ss->next;
			delete bb;
			delete ss;
			return head;
		}
};


int main()
{
	int i,j;
	ListNode * head=new ListNode(3);
	ListNode * tail=head;
	for(int i=2;i>=1;i--)
	{
		ListNode * temp=new ListNode(i);
		tail->next=temp;
		tail=temp;
	}
	show(head);
	Solution ans;
	tail=ans.insertionSortList(head);
	show(tail);
	return 0;
}








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值