单链表的删除

来源:互联网 发布:手机搜不到4g网络 编辑:程序博客网 时间:2024/05/01 09:16
  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 p=p->link;
  48. }
  49. if(p==NULL)
  50. printf("没有查找到该数据!");
  51. }
  52. stud * search2(stud *h,char *x) /*另一个查找函数,返回的是上一个查找函数的直接前驱结点的指针,*/
  53. /*h为表头指针,x为指向要查找的姓名的指针*/
  54. /*其实此函数的算法与上面的查找算法是一样的,只是多了一个指针s,并且s总是指向指针p所指向的结点的直接前驱,*/
  55. /*结果返回s即是要查找的结点的前一个结点*/
  56. {
  57. stud *p,*s;
  58. char *y;
  59. p=h->link;
  60. s=h;
  61. while(p!=NULL)
  62. {
  63. y=p->name;
  64. if(strcmp(y,x)==0)
  65. return(s);
  66. else
  67. {
  68. p=p->link;
  69. s=s->link;
  70. }
  71. }
  72. if(p==NULL)
  73. printf("没有查找到该数据!");
  74. }
  75. void del(stud *x,stud *y) /*删除函数,其中y为要删除的结点的指针,x为要删除的结点的前一个结点的指针*/
  76. {
  77. stud *s;
  78. s=y;
  79. x->link=y->link;
  80. free(s);
  81. }
  82. main()
  83. {
  84. int number;
  85. char fullname[20];
  86. stud *head,*searchpoint,*forepoint;
  87. number=N;
  88. head=creat(number);
  89. printf("请输入你要删除的人的姓名:");
  90. scanf("%s",fullname);
  91. searchpoint=search(head,fullname);
  92. forepoint=search2(head,fullname);
  93. del(forepoint,searchpoint);
原创粉丝点击