数据结构链表——删除值重复的结点

小灰灰 2022-12-24 11:52 219阅读 0赞
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<assert.h>
  4. typedef int Elemtype;
  5. typedef struct LNode{
  6. Elemtype data;
  7. struct LNode *next;
  8. }LNode,*Linklist;
  9. void Init_Linklist(Linklist *L)
  10. {
  11. *L=(Linklist)malloc(sizeof(LNode));
  12. assert(*L != NULL);
  13. (*L)->next=NULL;
  14. }
  15. void Create_Linklist(Linklist *L)
  16. {
  17. int n;
  18. LNode *p,*q;
  19. p = *L;
  20. printf("链表的长度:");
  21. scanf("%d",&n);
  22. printf("输入链表元素:\n");
  23. for(int i=0;i<n;i++)
  24. {
  25. q=(Linklist)malloc(sizeof(LNode));
  26. assert( q != NULL);
  27. scanf("%d",&q->data);
  28. p->next=q;
  29. p=q;
  30. }
  31. p->next=NULL;
  32. }
  33. void DeleteSame(Linklist *L)
  34. {
  35. LNode *p,*q,*s;
  36. p = (*L)->next;
  37. for(p;p!=NULL;p=p->next)
  38. {
  39. s=p; //s指向要删除结点的前驱
  40. for(q=p->next;q!=NULL; )
  41. {
  42. if(q->data==p->data)
  43. {
  44. s->next=q->next;
  45. free(q);
  46. q=s->next;
  47. }
  48. else
  49. {
  50. s=q;
  51. q=q->next;
  52. }
  53. }
  54. }
  55. }
  56. void Print_Linklist(Linklist *L)
  57. {
  58. LNode *p;
  59. p = *L;
  60. while(p->next)
  61. {
  62. p=p->next;
  63. printf("%d ",p->data);
  64. }
  65. printf("\n");
  66. }
  67. int main()
  68. {
  69. Linklist L;
  70. Init_Linklist(&L);
  71. Create_Linklist(&L);
  72. printf("初始化链表为:\n");
  73. Print_Linklist(&L);
  74. DeleteSame(&L);
  75. printf("删除后链表为:\n");
  76. Print_Linklist(&L);
  77. return 0;
  78. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,219人围观)

还没有评论,来说两句吧...

相关阅读

    相关 删除重复

    写在前面 > 剑指offer:删除链表中重复的结点 题目要求 > 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。