单链表的插入
来源:互联网 发布:手机搜不到4g网络 编辑:程序博客网 时间:2024/05/01 06:51
- #include <stdio.h>
- #include <malloc.h>
- #include <string.h>
- #define N 10
- typedef struct node
- {
- char name[20];
- struct node *link;
- }stud;
- stud * creat(int n)
- {
- stud *p,*h,*s;
- int i;
- if((h=(stud *)malloc(sizeof(stud)))==NULL)
- {
- printf("不能分配内存空间!");
- exit(0);
- }
- h->name[0]='/0';
- h->link=NULL;
- p=h;
- for(i=0;i<n;i++)
- {
- if((s= (stud *) malloc(sizeof(stud)))==NULL)
- {
- printf("不能分配内存空间!");
- exit(0);
- }
- p->link=s;
- printf("请输入第%d个人的姓名:",i+1);
- scanf("%s",s->name);
- s->link=NULL;
- p=s;
- }
- return(h);
- }
- stud * search(stud *h,char *x)
- {
- stud *p;
- char *y;
- p=h->link;
- while(p!=NULL)
- {
- y=p->name;
- if(strcmp(y,x)==0)
- return(p);
- else
- p=p->link;
- }
- if(p==NULL)
- printf("没有查找到该数据!");
- }
- void insert(stud *p)
- {
- char stuname[20];
- stud *s;
- if((s= (stud *) malloc(sizeof(stud)))==NULL)
- {
- printf("不能分配内存空间!");
- exit(0);
- }
- printf("请输入你要插入的人的姓名:");
- scanf("%s",stuname);
- strcpy(s->name,stuname);
- s->link=p->link;
- p->link=s;
- }
- main()
- {
- int number;
- char fullname[20];
- stud *head,*searchpoint;
- number=N;
- head=creat(number);
- printf("请输入你要查找的人的姓名:");
- scanf("%s",fullname);
- searchpoint=search(head,fullname);
- insert(searchpoint);
- }