问题描述
- 各位给菜鸟看看在下万分感谢~~
-
#include
#include
#define LEN sizeof(struct student)struct student
{
char name[20];int num;
double score;
struct student *next;
};int n;
struct student* creat() //定义函数此函数带回头指针
{
struct student *head;
struct student *p1,*p2;head=NULL; n=0; p1 = p2=(struct student*)malloc(LEN); //开辟动态的存储空间 printf("输入姓名:"); scanf("%s",&p1->name); printf("输入学号:"); scanf("%d",&p1->num); printf("输入成绩:"); scanf("%lf",&p1->score); while(p1->num!=0) { n++; if(n==1) //如果n==1 { head=p1; //使head指向新开辟的节点 } else { p2->next=p1; //如果n!=1 p2为2时指向第一个节点地址 p2=p1; //p2指向刚才开辟的节点 } p1=(struct student*)malloc(LEN); printf("输入姓名:"); scanf("%s",&p1->name); printf("输入学号:"); scanf("%d",&p1->num); printf("输入成绩:"); scanf("%lf",&p1->score); } p2->next=NULL; //最后放入NULL return head; //返回头指针
}
void print(struct student *head)
{
struct student *p;
int t=1;
printf("n本名单有%d名学生n",n);
p=head;if(head) { do { printf("第%d个学生是 n",t++); printf("姓名:%sn",p->name); printf("学号:%dn",p->num); printf("成绩:%lfn",p->score); p=p->next; //指向下一个地址 }while(p!=NULL); }
}
struct student Inssert(struct student*head,struct student *stu)
{
struct student *p0,*p1,*p2;
p1=head;
p0=stu;if(head==NULL)//原来的链表是空表 { head=p0; p0->next=NULL; } else { while((p0->num>p1->num)&&(p1->next!=0)) { p2=p1; p1=p1->next; } if(p0->num<=p1->num) { if(head==p1) head=0; else p2->next=p0; p0->next=p1; } else { p1->next=p0; p0->next=NULL; } n=n+1; return head; }
}
void main()
{
struct student *head,stu;
head=creat();
head=Inssert(head,&stu);
print(head);
}
时间: 2024-10-23 04:42:24