- #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("没有查找到该数据!");
- }
- stud * search2(stud *h,char *x) /*另一个查找函数,返回的是上一个查找函数的直接前驱结点的指针,*/
- /*h为表头指针,x为指向要查找的姓名的指针*/
- /*其实此函数的算法与上面的查找算法是一样的,只是多了一个指针s,并且s总是指向指针p所指向的结点的直接前驱,*/
- /*结果返回s即是要查找的结点的前一个结点*/
- {
- stud *p,*s;
- char *y;
- p=h->link;
- s=h;
- while(p!=NULL)
- {
- y=p->name;
- if(strcmp(y,x)==0)
- return(s);
- else
- {
- p=p->link;
- s=s->link;
- }
- }
- if(p==NULL)
- printf("没有查找到该数据!");
- }
- void del(stud *x,stud *y) /*删除函数,其中y为要删除的结点的指针,x为要删除的结点的前一个结点的指针*/
- {
- stud *s;
- s=y;
- x->link=y->link;
- free(s);
- }
- main()
- {
- int number;
- char fullname[20];
- stud *head,*searchpoint,*forepoint;
- number=N;
- head=creat(number);
- printf("请输入你要删除的人的姓名:");
- scanf("%s",fullname);
- searchpoint=search(head,fullname);
- forepoint=search2(head,fullname);
- del(forepoint,searchpoint);
单链表的删除
最新推荐文章于 2024-03-24 12:51:40 发布