单链表排序程序

struct node
{
	int num;
    node *next;
};
/*按照从小到大的顺序插入节点p,返回头节点*/
node* insertNode(node *head,node *p)
{
	if(p->num<head->num)
	{
		p->next=head;
		return p;
	}
	insertNode(head->next,p);
	return head;
}
/*单链表插入排序*/
node* insertSort(node * head)
{
	for(node *pCur=head;pCur->next;)
	{
		/*只能从前往后插*/
		if(pCur->num>pCur->next->num)
		{
			node *pNext=pCur->next;
			pCur->next=pCur->next->next;
			head=insertNode(head,pNext);
		}
		else
		{
			pCur=pCur->next;
		}
	}
	return head;
}

/*单链表选择排序*/
node * selectSort(node *head)
{
	node * tmp=new node;
	tmp->next=head;
	head=tmp;

	node *pCur;//用于遍历链表的指针
	node *pPreMin;//指向当前链表最小值节点的前一个节点
	node*pMin;//指向当前链表最小值节点
	node *rhead=NULL;

	while(head->next)
	{
		for(pCur=head,pPreMin=pCur;pCur->next;pCur=pCur->next)
		{
			if(pPreMin->next->num>pCur->next->num)
				pPreMin=pCur;
		}

		pMin=pPreMin->next;
		pPreMin->next=pMin->next;
		pMin->next=rhead;
		rhead=pMin;
	}
	delete head;
	return rhead; 
}

/*单链表冒泡排序*/
void bubbleSort(node **head)
{
	node * tmp=new node;
	tmp->next=*head;
	*head=tmp;

	node *end=NULL;
	node *pPre,*pCur;

	while((*head)->next!=end)
	{	
		for(pPre=*head,pCur=pPre->next;pCur->next!=end;)
		{
			if(pCur->num>pCur->next->num)
			{
				/*交换pCur和pCur->next的位置*/
				pPre->next=pCur->next;
				pCur->next=pPre->next->next;
				pPre->next->next=pCur;
			}
			pPre=pPre->next;
			pCur=pPre->next;
		}
		end=pCur;
	}
	*head=(*head)->next;
	delete tmp;
}
/*测试程序*/
node * createNode(int *num,int len)
{
	node * head=new node[len];
	node *p=head;
	for(int i=0;i<len;i++)
	{
		p->num=num[i];
		p->next=p+1;
		p++;
	}
	(--p)->next=NULL;
	return head;
}
void main()
{
	int num[]={10,9,87,6,5,4,3,2,1,109};
	node *head=createNode(num,10);
	head=selectSort(head);
	head=insertSort(head);
	bubbleSort(&head);
	while(head)
	{
		cout<<head->num<<endl;
		head=head->next;
	}
	system("pause");
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值