首页 > 代码库 > P330.9 实验报告 创建动态链表实现插入删除

P330.9 实验报告 创建动态链表实现插入删除

#include<stdio.h>

#include<stdlib.h>

#define LEN sizeof(struct Student)

struct Student {  long num;  char name[20];  int age;  float score;  struct Student *next; };

int n;

struct Student *creat()

{  struct Student*head;  

struct Student *p1,*p2;  

n=0;  

p1=p2=(struct Student*)malloc(LEN);

 printf("Please enter the student num\t");  

scanf("%d",&p1->num);  

if (p1->num==0)   

return head=NULL;  

printf("Please enter the student name\t");  scanf("%s",p1->name);  

printf("Please enter the student age\t");  scanf("%d",&p1->age);  

printf("Please enter the student score\t");  scanf("%f",&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);

      printf("Please enter the student num\t");

     scanf("%d",&p1->num);

  if (p1->num==0){    p2->next=NULL;    return head;   }

     printf("Please enter the student name\t");

  scanf("%s",p1->name);

     printf("Please enter the student age\t");

     scanf("%d",&p1->age);      

printf("Please enter the student score\t");

     scanf("%f",&p1->score);  }

}

void print(struct Student *head)

{  

struct Student *p;

 printf("\nNow,These %d records are:\n",n);

 p=head;

 if(head!=NULL)   do

  {printf("%d\t%s\t%d\t%.1lf\n",p->num,p->name,p->age,p->score); p=p->next;   }

while(p!=NULL);

}

struct Student *insert(struct Student *head)

{  

struct Student *p1,*p2,*p3;  

p2=head;  

p1=(struct Student*)malloc(LEN);  

printf("Now you can insert new student\n");  

printf("Please enter the student num\t");

 scanf("%d",&p1->num);  

printf("Please enter the student name\t");  

scanf("%s",p1->name);  

printf("Please enter the student age\t");  

scanf("%d",&p1->age);  

printf("Please enter the student score\t");  

scanf("%f",&p1->score);

 if(head==NULL)  {   head=p1;   p1->next=NULL;  }

 else  

{   

while( (p1->num>p2->num)&&(p2->next!=NULL))   {    p3=p2;    p2=p2->next;   }

  if(p1->num<p2->num)   

{   

 if(head==p2)    {     head=p1;     p1->next=p2;    }

   else    {     p3->next=p1;     p1->next=p2;    }  

}   

else  

 {    p2->next=p1;    p1->next=NULL;   }

 }   

n=n+1;   

return head; }

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;  }  

if(num==p1->num)  

{   if(p1==head)    head=p1->next;

  else    p2->next=p1->next;

  printf("delete :%d\n",num);  

 n-=1;  

 free(p1);  }  

else   printf("num not found\n");  

return head;

}

void main()

{  struct Student *head;  int num;

 head=creat();  print(head);

 head=insert(head);  print(head);

 printf("enter delete number\n");  scanf("%d",&num);

 head=del(head,num);     print(head);

}

P330.9 实验报告 创建动态链表实现插入删除