
#include "stdafx.h"
#include "malloc.h"
#include "stdlib.h"
#include "stdio.h"
#define NULL 0
#define LEN sizeof(struct student)

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

int n;//n为全局变量,指结点数

struct student *creat(void)
  {
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(LEN);//开辟结点,使p1、p2指向它
scanf("%ld%f",&p1->num,&p1->score);
head=NULL;//此时链表中无结点
while(p1->num!=0)//约定学生学号不为0,如果学号为0,代表链表创建结束
 {
n=n+1;
if(n==1)//判断是否是第一个结点
head=p1;//head指向首结点
else
p2->next=p1;//将新结点的地址赋给p2结点的next成员
p2=p1;//p2指向新结点
p1=(struct student *)malloc(LEN);
scanf("%ld%f",&p1->num,&p1->score);
}
p2->next=NULL;//链表创建过程结束
return(head);
}

void print(struct student *head)
  {
struct student *p;
printf("\nNow,these %d records are:\n",n);
p=head;//p指向第一个结点
if(head!=NULL)
do
 {
printf("%ld%5.1f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}

struct student *del(struct student *head,long num)
  {
struct student *p1,*p2;
if(head==NULL)//判断链表是否为空
 {
printf("\nlist null!\n");
}
else
 {
p1=head;
while(num!=p1->num&&p1->next!=NULL)
 {
p1=p2;
p1=p1->next;//p1后移一个结点
}
if(num==p1->num)
 {
if(p1==head)
head=p1->next;
else
p2->next=p1->next;//让p1的前一个结点指向其后一个结点
printf("delete:%ld\n",num);
n=n-1;
}
else
printf("%ld not been found!",num);//找不到该结点
}
return(head);
}

struct student *insert(struct student *head,struct student *stud)
  {
struct student *p0,*p1,*p2;
p1=head;//p1指向第一个结点
p0=stud;//p0指向要插入的节点
if(head==NULL)//判断链表是否为空
 {
head=p0;
p0->next=NULL;//p0指向的结点作为头结点
}
else
 {
while((p0->num>p1->num)&&(p1->next!=NULL))
 {
p2=p1;
p1=p1->next;//p1后移一个结点
}
if(p0->num<=p1->num)
 {
if(head==p1)//p0是头结点
head=p0;
else
p2->next=p0;
p0->next=p1;
}
else//p0是尾结点
 {
p1->next=p0;
p0->next=NULL;
}
}
n=n+1;//结点数加1
return(head);
}

void main()
  {
struct student *head,*stu;
long del_num;
printf("input records:\n");
head=creat();
print(head);
printf("\ninput the deleted number:");
scanf("%ld",&del_num);
while(del_num!=0)
 {
head=del(head,del_num);
print(head);
printf("\ninput the deleted number:");
scanf("%ld",&del_num);
}
printf("\ninput the inserted record:");
stu=(struct student *)malloc(LEN);
scanf("%ld%f",&stu->num,&stu->score);
while(stu->num!=0)
 {
head=insert(head,stu);
print(head);
printf("\ninput the inserted record:");
stu=(struct student *)malloc(LEN);
scanf("%ld%f",&stu->num,&stu->score);
}
free(head);
system("Pause");
}


|