当前位置:   article > 正文

编写程序删除单链表中所有值为x的节点--重制版_c语言实现单链表删除x

c语言实现单链表删除x

思路非常简单,就是查找出一个节点p满足值为x,将前驱节点q指向后继节点,然后将此节点删除即可。值得注意的是头节点head为此值时要分开讨论,即直接让头节点的后继节点成为新的头节点。

  1. #include<stdio.h>
  2. #include<math.h>
  3. #include<malloc.h>
  4. typedef struct node {
  5. int data;
  6. struct node* next;
  7. }node;
  8. node* Delete(node* head,int x) {
  9. node* p = head;
  10. node* q = NULL;
  11. while (p) {
  12. if (p->data == x&&p==head) {
  13. node* m = head;
  14. q = p;
  15. head = head->next;
  16. p = head;
  17. free(m);
  18. }
  19. else if (p->data == x) {
  20. q->next = p->next;
  21. node* m = p;
  22. p = p->next;
  23. free(m);
  24. }
  25. else {
  26. q = p;
  27. p = p->next;
  28. }
  29. }
  30. return head;
  31. }
  32. int main() {
  33. node* a = (node*)malloc(sizeof(node)); a->data = 1;
  34. node* b = (node*)malloc(sizeof(node)); b->data = 2;
  35. node* c = (node*)malloc(sizeof(node)); c->data = 3;
  36. node* d = (node*)malloc(sizeof(node)); d->data = 2;
  37. a->next = b; b->next = c; c->next = d; d->next = NULL;
  38. node* p = (node*)malloc(sizeof(node));
  39. p = Delete(a, 2);
  40. while (p) {
  41. printf("%d", p->data);
  42. p = p->next;
  43. }
  44. return 0;
  45. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/444246
推荐阅读
相关标签
  

闽ICP备14008679号