单链表的插入

来源:互联网 发布:手机搜不到4g网络 编辑:程序博客网 时间:2024/05/01 06:51
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <string.h>
  4. #define N 10
  5. typedef struct node
  6. {
  7.     char name[20];
  8.     struct node *link;
  9. }stud;
  10. stud * creat(int n) /*建立单链表的函数*/
  11. {
  12.     stud *p,*h,*s;
  13.     int i;
  14.     if((h=(stud *)malloc(sizeof(stud)))==NULL)
  15.     {
  16.         printf("不能分配内存空间!");
  17.     exit(0);
  18.     }
  19.     h->name[0]='/0';
  20.     h->link=NULL;
  21.     p=h;
  22.     for(i=0;i<n;i++)
  23.     {
  24.         if((s= (stud *) malloc(sizeof(stud)))==NULL)
  25.         {
  26.             printf("不能分配内存空间!");
  27.             exit(0);
  28.         }
  29.         p->link=s;
  30.         printf("请输入第%d个人的姓名:",i+1);
  31.         scanf("%s",s->name);
  32.         s->link=NULL;
  33.         p=s;
  34.     }
  35.     return(h);
  36. }
  37. stud * search(stud *h,char *x) /*查找函数*/
  38. {
  39.     stud *p;
  40.     char *y;
  41.     p=h->link;
  42.     while(p!=NULL)
  43.     {
  44.         y=p->name;
  45.         if(strcmp(y,x)==0)
  46.             return(p);
  47.         else
  48.             p=p->link;
  49.     }
  50.     if(p==NULL)
  51.         printf("没有查找到该数据!");
  52. }
  53. void insert(stud *p) /*插入函数,在指针p后插入*/
  54. {
  55.     char stuname[20];
  56.     stud *s; /*指针s是保存新结点地址的*/
  57.     if((s= (stud *) malloc(sizeof(stud)))==NULL)
  58.     {
  59.         printf("不能分配内存空间!");
  60.         exit(0);
  61.     }
  62.     printf("请输入你要插入的人的姓名:");
  63.     scanf("%s",stuname);
  64.     strcpy(s->name,stuname); /*把指针stuname所指向的数组元素拷贝给新结点的数据域*/
  65.     s->link=p->link; /*把新结点的链域指向原来p结点的后继结点*/
  66.     p->link=s; /*p结点的链域指向新结点*/
  67. }
  68. main()
  69. {
  70.     int number;
  71.     char fullname[20]; /*保存输入的要查找的人的姓名*/
  72.     stud *head,*searchpoint;
  73.     number=N;
  74.     head=creat(number); /*建立新链表并返回表头指针*/
  75.     printf("请输入你要查找的人的姓名:");
  76.     scanf("%s",fullname);
  77.     searchpoint=search(head,fullname); /*查找并返回查找到的结点指针*/
  78.     insert(searchpoint); /*调用插入函数*/
原创粉丝点击