1101 [填空题]链表的排序 SCAU

题目:先创建一个链表(链表中各结点未按学号由小到大排序),然后调用sort函数,将链表中各结点按学号由小到大排序

法一(超时)
这个题我一开始的思路是利用冒泡的思想,当当前结点比next结点大的时候,交换两者next所指向内容。
比如链表1-5-4-6 , 当指针p指向5所在结点的时候,发现p->next的num小于当前的num,这时候我要令p1=p->next(4所在结点), 让(5)p->next指向 (6)p1->next, 再让 (4)p1->next指向(5)p,最后再让(1)pre接上(4)p1,这样,链表的结点顺序就变成了 1-4-5-6。(注意如果是第一位的话就不用使用pre指针)

#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct student)

struct student
{
   
     long num;
     int score;
     struct student *next;
};

struct student *create(int n)
{
   
     struct student *head=NULL,*p1=NULL,*p2=NULL;
     int i;
     for(i=1;i<=n;i++)
     {
     p1=(struct student *)malloc(LEN);
        scanf("%ld",&p1->num);
        scanf("%d",&p1->score);
        p1->next=NULL;
        if(i==1) head=p1;
        else p2->next=p1;
        p2=p1;
      }
      return(head);
}

void print(struct student *head)
{
   
    struct student *p;
    p=head;
    while(p!=NULL)
    {
   
        printf("%8ld%8d",p->num,p->score);
        p=p->next;
        printf("\n");
    }
}

struct student *insert(struct student *head, struct student *stud)
{
     struct student *p0,*p1,*p2;
    p1=head;  p0=stud;
    if(head==NULL)
      {
   head=p0;}
    else
   
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值