|
源代码网推荐
源代码网整理以下3、删除 源代码网推荐假如我们已经知道了要删除的结点p的位置,那么要删除p结点时只要令p结点的前驱结点的链域由存储p结点的地址该为存储p的后继结点的地址,并回收p结点即可。 源代码网推荐以下便是应用删除算法的实例: 源代码网推荐#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); 源代码网供稿. |