链表的综合使用

来源:互联网 发布:淘宝ipad版本 编辑:程序博客网 时间:2024/05/16 18:51

/*链表的使用*/

/*创建*/
#include<malloc.h> /*分配空间*/

#define NULL 0
#define LEN sizeof(struct student)

struct student /*定义结构体*/
{
 long num;
 float score;
 struct student *next;
};

int n;/*全局变量,记录结点个数*/

struct student *creat(void)
{
 struct student *head;
 struct student *p1,*p2;
 n=0;
 p1=p2=(struct student *)malloc(LEN);/*开辟一个新单元*/
 scanf("%ld,%f",&p1->num,&p1->score);
 head=NULL;
 while(p1->num!=0)
 {
  n=n+1;
  if(n==1)head=p1;
  else p2->next=p1;
  p2=p1;
  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, there %d records are:/n",n);
 p=head;
 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");return(head);}
 p1=head;
 while(num!=p1->num&&p1->next!=NULL)/*查找*/
 {
  p2=p1;
  p1=p1->next;/*p1往后移*/
 }
 if(num==p1->num) /*找到*/
 {
  if(p1==head)/*如果是首结点*/
   head=p1->next;
  else 
   p2->next=p1->next;
  printf("delete:%ld/n",num);
  n=n-1;
 }
 else
  printf("%ld not been found!/n",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;
 }
 else
 {
  while((p0->num>p1->num)&&p1->next!=NULL)
  {
   p2=p1;/*p2指向p1所指的结点*/
   p1=p1->next;/*p1指向下一个结点*/
  }
  if(p0->num<=p1->num)
  {
   if(head==p1)/*如果是首结点*/
   {
    head=p0;
   }
   else
    p2->next=p0;
   p0->next=p1;
  }
  else/*如果新结点的数比所有结点的数都大,则插到最后*/
  {
   p1->next=p0;
   p0->next=NULL;
  }
 }
 n=n+1;/*插入工作完成后,结点数加1*/
 return(head);
}


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); /*插入后输出*/
  stu=(struct student *)malloc(LEN);
  scanf("%ld,%f",&stu->num,&stu->score);
 }
}