以学生的学号、成绩为基础,实现链表的有序创建、插入、删除的功能。
/********************************************************************************
* 该程序以学生的学号、成绩为基础,实现了链表的有序创建、插入、删除的功能。 *
********************************************************************************/
#include
#include
#define LEN sizeof(struct Student)
struct Student
{
long num;
double score;
struct Student *next;
};
int n=0; //记录结点个数
//====================================================================
struct Student *insert(struct Student *head,struct Student *stud) //有序插入链表
{
struct Student *p0,*p1,*p2;
p0 = stud;
if(head == NULL) //处理表头为空
{
head = p0;
p0->next = NULL;
}
else
{
p1 = head;
//while(p1->next != NULL && p0->num > p1->num)
//{
//p2 = p1;
//p1 = p1->next;
//}
//if(p0->num <= p1->num)
//{
//if(p1 == head)
//head = p0;
//else
//p2->next = p0;
//p0->next = p1;
//}
//else
//{
//p1->next = p0;
//p0->next = NULL;
//}
while(p1 != NULL && p1->num < p0->num) //上面注释部分与下面的程序块功能
{ // 相同,为不同实现方法
p2 = p1; //
p1 = p1->next; //
} //
if(p1 == head) //处理插入表头之前
head = p0; //
else //
p2->next = p0; //表中
p0->next = p1; //表尾
}
n++;
return(head);
}
//=====================================================================
struct Student *creat() //创建链表
{
struct Student *head,*p1;
head = NULL;
printf("Please input the number and score of the student:\n");
p1=(struct Student *)malloc(LEN);
scanf("%ld,%lf",&p1->num,&p1->score);
while(p1->num != 0) //以0结束
{
head=insert(head,p1);
printf("Please input the number and score of the student:\n");
p1=(struct Student *)malloc(LEN);
scanf("%ld,%lf",&p1->num,&p1->score);
}
return(head);
}
//=====================================================================
struct Student *dell(struct Student *head,long num) //删除链表结点
{
struct Student *p1,*p2;
if(head == NULL) //处理链表为空的情况
{
printf("This is a void excel.\n");
return(head);
}
p1 = head;
while(p1->num != num && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if(p1->num == num)
{
if(p1 == head) //删除结点为表头
head = p1->next;
else //表中、表尾
p2->next = p1->next;
printf("The number y
ou have deleted is:%ld\n",num);
free(p1); //释放空间
n--;
}
else
printf("Sorry,the number you want to delete is not found