https://leetcode.com/problems/remove-linked-list-elements/

1. Use two pointers:

  1. //36 ms 10.6 MB
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. * int val;
  6. * ListNode *next;
  7. * ListNode(int x) : val(x), next(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. ListNode* removeElements(ListNode* head, int val) {
  13. if(!head) return NULL;
  14. ListNode* dummy = new ListNode(-1);
  15. dummy->next = head;
  16. ListNode* curr = dummy->next;
  17. ListNode* prev = dummy;
  18. while(curr){
  19. if(curr && curr->val == val){
  20. prev->next = curr->next;
  21. curr->next = NULL;
  22. curr = prev->next;
  23. } else{
  24. curr = curr->next;
  25. prev = prev->next;
  26. }
  27. }
  28. return dummy->next;
  29. }
  30. };