//输入10个学生的基本信息(学号、姓名、成绩),要求按学号从小到大的顺序输入,
//建立一个单向链表。输入一个学生的学号num,姓名name和成绩score,查找链表中
//是否有学号为num的结点,若找到,则删除改节点,否则按学号顺序将该学生的信息
//插入链表中。最后输出链表中各结点的数据。
//提示:定义结构体数据类型student,包括4个数据成员;编写函数creat,实现链表的建立,返回链表的头指针;
//编写函数print,将链表各个结点的内容输出;编写函数find,查找某结点;编写函数delete删除学号为num的结点,
//返回链表的头指针;编写函数insert,将学号按照num的学生信息按照学号的升序插入链表,返回链表的头指针;
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
long num;//存放学号
char name[10];//存放姓名
double score;//存放成绩
struct student *next;//指向结构体数据类型的指针
};
void main()
{
struct student *create(int);
void print(struct student *);
int find (struct student *,long);
struct student *delet(struct student *,long);
struct student *insert(struct student *,struct student *);
struct student *head,*p;
long num;
char name[10];
double score;
head=create(10);//返回链表的头指针
printf("The list is:\n");
print(head);//输出创建的链表
printf("Input a num:\n");
scanf("%ld",&num);//输入要查找的学号
if ( find(head,num) )//若找到该结点
{
head=delet(head,num);//删除结点
printf("After deleting the node of %ld,the list is:\n",num);
print(head);
}
else //该结点不存在,进行插入操作
{
printf("The node of %ld not been found!\n",num);
printf("Input the name and score of the student %ld:\n",num);
scanf("%s%lf",name,&score);//输入该结点其他两个数据成员
p=(struct student *)malloc(sizeof(struct student));//申请新结点空间
p->num=num;//给新结点赋值
strcpy(p->name,name);
p->score=score;
p->next=NULL;
head=insert(head,p);//返回插入后链表的头指针
printf("After inserting the node of %ld,the list is:\n",num);
print(head);
}
}
struct student *create(int n)
{
int i;
long num;
char name[10];
double score;
struct student *head=NULL,*pnew,*ptail;
for(i=1;i<=n;i++)
{
pnew=(struct student *)malloc(sizeof(struct student));//申请新结点
printf("Input a num,name and score:\n");
scanf("%ld%s%lf",&num,name,&score);
pnew->num=num;
strcpy(pnew->name,name);
pnew->score=score;
if (head==NULL) head=ptail=pnew;//若是头结点
else
{
ptail->next=pnew;//尾结点
ptail=pnew;
}
}
ptail->next=NULL;
return head;
}
void print(struct student *head)
{
struct student *p=head;
while(p!=NULL)
{
printf("%ld,%s,%.1lf\n",p->num,p->name,p->score);
p=p->next;
}
}
int find(struct student *head,long num)
{
struct student *p;
p=head;
while (p!=NULL&&p->num!=num)//顺序查找结点
p=p->next;
if( p!=NULL) return 1;
else return 0;
}
struct student *delet(struct student *head ,long num)
{
struct student *pp,*p;
p=pp=head;
while(p!=NULL&&p->num!=num)//查找结点
{
pp=p;
p=p->next;
}
if(head==p)head=p->next;//找到的是链表的头结点
else pp->next=p->next;
free(p);
printf("%ld has been delete!\n",num);
return head;//返回删除结点后的链表的头指针
}
struct student *insert(struct student *head,struct student *pnew)
{
struct student *pp,*p;
p=pp=head;
if (head==NULL) head=pnew;//若是空表
else
if (p->num>pnew->num)//插入到原来的头结点之前
{
pnew->next=p;
head=pnew;
}
else
{
while(p!=NULL&&p->num<pnew->num)//查找插入点
{
pp=p;
p=p->next;
}
pnew->next=p;//插入到pp指向的结点之后
pp->next=pnew;
}
return head;//返回插入结点后链表的头指针
}