203. Remove Linked List Elements 發表於 2023-02-13 | 分類於 leetcode problemsolutionoption 1 - Two Pointers1234567891011121314151617class Solution {public: ListNode* removeElements(ListNode* head, int val) { ListNode *slow = new ListNode(-1), *fast=head, *ret = slow; slow->next = head; while(fast){ if(fast->val!=val) { slow->next = fast; slow=slow->next; } fast=fast->next; } slow->next = nullptr; return ret->next; }}; option 2123456789101112class Solution {public: ListNode* removeElements(ListNode* head, int val) { ListNode *cur = new ListNode(-1), *ret = cur; cur->next = head; while(cur){ if(cur->next && cur->next->val == val) cur->next = cur->next->next; else cur = cur->next; } return ret->next; }}; 12345678910111213class Solution {public: ListNode* removeElements(ListNode* head, int val) { ListNode *cur = new ListNode(-1), *ret = cur; cur->next = head; while(cur){ while(cur->next && cur->next->val ==val) cur->next=cur->next->next; cur = cur->next; } return ret->next; }}; analysis time complexity O(n) space complexity O(1)