当前位置:   article > 正文

移除链表元素

移除链表元素

法一:在原链表上删除

  1. struct SListNode* removeElements(struct SListNode* head, int val)
  2. {
  3. if (head == NULL)
  4. return NULL;
  5. while (head->data == val)
  6. {
  7. struct SListNode* del = head;
  8. head = del->next;
  9. free(del);
  10. del = NULL;
  11. if (head == NULL)
  12. break;
  13. }
  14. if (head == NULL)
  15. return NULL;
  16. struct SListNode* cur = head;
  17. while (cur->next != NULL)
  18. {
  19. if (cur->next->data == val)
  20. {
  21. struct SListNode* del = cur->next;
  22. cur->next = del->next;
  23. free(del);
  24. del = NULL;
  25. }
  26. else
  27. {
  28. cur = cur->next;
  29. }
  30. }
  31. return head;
  32. }

法二:创建新的链表

  1. struct SListNode* removeElements(struct SListNode* head, int val)
  2. {
  3. struct SListNode* pcur = NULL, * pend = NULL;
  4. struct SListNode* cur = head;
  5. if (cur == NULL)
  6. return NULL;
  7. else
  8. {
  9. while (cur != NULL)
  10. {
  11. if (cur->data != val)
  12. {
  13. if (pcur == NULL)
  14. pcur = pend = cur;
  15. else
  16. {
  17. pend->next = cur;
  18. pend = cur;
  19. }
  20. }
  21. cur = cur->next;
  22. }
  23. if (pend != NULL)
  24. pend->next = NULL;
  25. head = pcur;
  26. return head;
  27. }
  28. }

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

闽ICP备14008679号