Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
利用快慢两个指针
注意设置的头结点是临时局部变量
ListNode* removeElements(ListNode* head, int val) { ListNode dummy(0); dummy.next = head; ListNode* slow = &dummy, *fast = head; while (fast != nullptr) { if (fast->val != val) { slow->next = fast; slow = slow->next; } fast = fast->next; } slow->next = nullptr; return dummy.next; }