本题要求实现,将输入的学生信息组成单向链表(要求按学号由小到大的顺序输入学生信息);添加一个新的学生信息,并保持学生信息仍然按学号由小到大的顺序。
函数接口定义:
struct stud_node *create();
struct stud_node *insertdata( struct stud_node *head, int n,char name[],int s );
函数create利用scanf从输入中获取一系列正整数,当读到0时表示输入结束。要求按学号由小到大的顺序输入学生信息。
裁判测试程序样例:
解释
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN sizeof(struct stud_node)
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *create();
struct stud_node *insertdata( struct stud_node *head, int n,char name[],int s );
int main()
{
int num,score;
char name[20];
struct stud_node *p, *head = NULL;
head = create();
scanf("%d%s%d",&num,name,&score);
head=insertdata(head,num,name,score);
for ( p = head; p != NULL; p = p->next )
printf("%d %s %d\n", p->num, p->name, p->score);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例1:
解释
10001 zhang 96 10003 wang 63 0 10002 liu 100
输出样例1:
10001 zhang 96
10002 liu 100
10003 wang 63
输入样例2:
解释
10001 zhang 96 10002 liu 100 10003 wang 63 0 10004 zhao 90
输出样例2:
解释
10001 zhang 96 10002 liu 100 10003 wang 63 10004 zhao 90
输入样例3:
解释
10001 zhang 96 10002 liu 100 10003 wang 63 10004 zhao 90 0 10000 sun 95
输出样例3:
解释
10000 sun 95 10001 zhang 96 10002 liu 100 10003 wang 63 10004 zhao 90
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
struct stud_node *create()
{
struct stud_node *p2,*p1,*head;
head=NULL;
int n=0;
p1=p2=(struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d",&p1->num);
while(p1->num!=0)
{
scanf("%s %d",p1->name,&p1->score);
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d",&p1->num);
}
p2->next=NULL;
return(head);
}
struct stud_node *insertdata( struct stud_node *head, int n,char name[],int s )
{
struct stud_node *p=head,*pr=head,*q=head;
p=(struct stud_node*)malloc(sizeof(struct stud_node));
p->next=NULL;
p->num=n;
strcpy(p->name,name);
p->score=s;
if(head==NULL)
head=p;
else
{
while(pr->num<n&&pr->next!=NULL)
{
q=pr;
pr=pr->next;
}
if(pr->num>=n)
{
if(pr==head)
{
p->next=head;
head=p;
}
else
{
pr=q;
p->next=pr->next;
pr->next=p;
}
}
else
{
pr->next=p;
}
}
return(head);
}