- #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) /*插入函数,在指针p后插入*/
- {
- char stuname[20];
- stud *s; /*指针s是保存新结点地址的*/
- if((s= (stud *) malloc(sizeof(stud)))==NULL)
- {
- printf("不能分配内存空间!");
- exit(0);
- }
- printf("请输入你要插入的人的姓名:");
- scanf("%s",stuname);
- strcpy(s->name,stuname); /*把指针stuname所指向的数组元素拷贝给新结点的数据域*/
- s->link=p->link; /*把新结点的链域指向原来p结点的后继结点*/
- p->link=s; /*p结点的链域指向新结点*/
- }
- main()
- {
- int number;
- char fullname[20]; /*保存输入的要查找的人的姓名*/
- stud *head,*searchpoint;
- number=N;
- head=creat(number); /*建立新链表并返回表头指针*/
- printf("请输入你要查找的人的姓名:");
- scanf("%s",fullname);
- searchpoint=search(head,fullname); /*查找并返回查找到的结点指针*/
- insert(searchpoint); /*调用插入函数*/
- }
单链表的插入
最新推荐文章于 2021-05-29 17:03:45 发布