题目

203 移除链表元素
题意:删除链表中等于给定值 val 的所有节点。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]

思路

本题很简单,就是遍历链表查找相等的节点并删除。唯一需要注意的是对head节点的处理。
我们使用虚拟头节点法,保证头节点的删除和中间节点的删除保持一致:

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution
  12. {
  13. public:
  14. ListNode *removeElements(ListNode *head, int val)
  15. {
  16. ListNode *tmpHead = new ListNode(0, head); //虚拟头节点
  17. ListNode *index = tmpHead;
  18. while (index->next != nullptr)
  19. {
  20. //当前节点有可能是虚拟头节点,所以直接判断下一节点值,并删除
  21. if (index->next->val == val)
  22. {
  23. ListNode *tmp = index->next;
  24. index->next = index->next->next;
  25. delete tmp;
  26. }
  27. else
  28. {
  29. index = index->next;
  30. }
  31. }
  32. head = tmpHead->next;
  33. delete tmpHead;
  34. return head;
  35. }
  36. };