排序算法--------qsort排序指针数组

qsort排序指针数组:
#include<stdlib.h>
#include<stdio.h>
//qsort排序指针数组
//定义一个结构体指针
typedef struct student_t{
	int num;//学生学号
	struct student_t *pNext;
}Student_t,*pStudent_t;

int comparePointer(const void* pleft,const void *pright){
	pStudent_t* p1=(pStudent_t*)pleft;
	pStudent_t* p2=(pStudent_t*)pright;//转换成二级指针
	return (*p1)->num-(*p2)->num;//p1是一个二级指针,对二级指针级应用就是一级指针
}

#define N 10
int main(){
	int i,listLen=0;
	pStudent_t phead,ptail,pNew,pCur;//定义结构体指针
	pStudent_t *pArr;//这是一个二级指针
	phead=ptail=NULL;
	//通过头插法新建链表
	while(scanf("%d",&i)!=EOF){
		pNew=(pStudent_t)calloc(1,sizeof(Student_t));//为每个结点申请空间
		pNew->num=i;//输入学生学号,存到结点中
		if (NULL==phead)
		{
			phead=pNew;
			ptail=pNew;

		}else
		{
			pNew->pNext=phead;
			phead=pNew;//头插法
		}
		listLen++;//链表长度+1
	}
	pArr=(pStudent_t*)calloc(listLen,sizeof(pStudent_t));//存储listen个数的指针
	pCur=phead;
	//遍历链表,将链表的每个结点的地址存入指针数组pArr
	for ( i = 0; i < listLen; i++)
	{
		pArr[i]=pCur;
		//pCur向后移动一个
		pCur=pCur->pNext;

	}
	//排序指针数组
	qsort(pArr,listLen,sizeof(pStudent_t),comparePointer);
	//打印排序后的效果
	printf("链表排序后的结点值:\n");
	for ( i = 0; i < listLen; i++)
	{
		printf("%3d",pArr[i]->num);

	}
	printf("\n");
	printf("链表本身的结点值(通过头插法建立的链表):\n");
	pCur=phead;
	while (pCur!=NULL)
	{
		printf("%3d",pCur->num);
		pCur=pCur->pNext;

	}
	printf("\n");
	//链表的销毁
	while (phead!=NULL)
	{
		pCur=phead;
		phead=phead->pNext;//作为下一个要删除的头
		free(pCur);
		pCur=NULL;
	}
	ptail=NULL;
	free(pArr);//释放指针数组的空间
	system("pause");

}













在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值