c语言——指针技巧——双指针定位法——指针排序,有序插入

6 篇文章 1 订阅
5 篇文章 0 订阅

 例题详解:

  1. 编写函数实现建立链表:struct student *  create( int n), n是学生人数。函数中输入n个学生的信息,同时计算总评成绩,按照总评成绩从高到低的方式形成有序链表。返回链表头指针。
  2. 结构体类型定义为:
  3. struct student {
    	int stunum;  		//学号
    	char name[20];	//姓名
    	float examscore;	//考试成绩
    	float labscore;	//实验成绩
    	float totalmark;	//总评成绩
    	struct student * next;  //下一个结点
    };
    

建立有序链表(边建立,边排序)

struct student *create(int n) {
	float t;
	int i,j;
	struct student *head,*p,*q,*qf;//p为新建;q,qf为移动节点,来夹住要插的节点
	
    p=(struct student*)malloc(sizeof (struct student));
	scanf("%d %s %f %f",&p->stunum,p->name,&p->examscore,&p->labscore);
	p->totalmark=p->examscore*0.6+p->labscore*0.4;
	p->next=NULL;//先创建一个节点

	head=p;
	p->next=NULL;//初始头+尾
	for(i=1; i<n; i++) {

		p=(struct student*)malloc(sizeof (struct student));
		scanf("%d %s %f %f",&p->stunum,p->name,&p->examscore,&p->labscore);
		p->totalmark=p->examscore*0.6+p->labscore*0.4;
		p->next=NULL;//先创建一个节点

		t=p->totalmark;//记录总评成绩
		q=head;//记录头指针
		if(t>=q->totalmark) { //若最大直接接到前面
			head=p;
			p->next=q;//头接法
		} else {
			while(q!=NULL&&t<q->totalmark) {
				qf=q;
				q=q->next;//小于q同时后移
			}
			qf->next=p;
			p->next=q;//插入到qf与q之间
		}
	}
	return(head);
}

注解·:本题与一般创建链表不同的是:要边建立边排序,因此需要双指针技巧

用p与pf(front)来夹住要插入的位置

要点:pf要在p后移之前承接p的位置,移动是并行的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值