链表的创建、查询、插入、删除

来源:互联网 发布:easyui js隐藏a标签 编辑:程序博客网 时间:2024/05/16 16:07
下面是function.c的代码:
#include<stdio.h>#include<malloc.h>#include "struct.h"struct student *creat(){   struct student *head,*p,*q;int i;struct student stu[4]={{2010,77},{2011,87},{2012,57},{2013,98}};p=(struct student *) malloc(LEN);p->num=stu[0].num;    p->score=stu[0].score;head=p;for(i=1;i<4;i++){  q=(struct student *) malloc(LEN);   q->num=stu[i].num;           q->score=stu[i].score;    p->next=q;   p=q;}p->next=NULL;return(head);}struct student *search(struct student *head,long num){struct student *p;p=head;while(p){if(p->num==num){  printf("the searched record is:num:%ld  score:%7.2f\n",p->num,p->score);  break;}p=p->next;}}struct student *delete(struct student *head,long num){struct student *p,*q;p=head;while(p){ if(head->num==num)   { head=p->next;     break;}  else   { if(p->num==num)      { q->next=p->next;        break;       }}  q=p;  p=p->next;}return(head);}struct student *insert(struct student *head,long N,long M,float L){struct student *p,*q;p=head;q=(struct student *) malloc(LEN);q->num=M;q->score=L;while(p) {   if(head->num==N)       {q->next=head->next;    head->next=q;    break;       } else { p=p->next;    if(p->num==N)           { q->next=p->next;             p->next=q; q=p; break;                 }     }}return(head);}void print(struct student *head){        struct student *p;        p=head;        printf("The records are:\n");        while(p)        {                printf("%ld %f\n",p->num,p->score);                p=p->next;        }}

 

下面是struct.h的代码:

#define LEN sizeof(struct student)struct student{    long num; float score; struct student *next;};struct student *creat();struct student *search();struct student *delete();struct student *insert();void print();

 

下面是main.c的代码:

#include<stdio.h>#include<malloc.h>#include "struct.h"int main(){        struct student *head;        int num,N,M,L;        head=creat();        print(head);        printf("please input searched record:\n");        scanf("%ld",&num);        search(head,num);printf("please input the goal record:\n");        scanf("%ld",&N);        printf("please input the inserted record:\n");        scanf("%ld %f",&M,&L);        head=insert(head,N,M,L);        print(head);        printf("please input the deleted record:\n");        scanf("%ld",&num);        head=delete(head,num);        print(head);        return 0;}




 

原创粉丝点击