203. Remove Linked List Elements
1. Description
Remove all elements from a linked list of integers that have value val.
2. Example
Example 1:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
3. Solutions
My Accepted Solution
n is the number of nodes in m_head
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
public:
// ListNode* removeElements(ListNode* head, int val)
ListNode* removeElements(ListNode *m_head, int val)
{
auto result = new ListNode();
result->next = m_head;
for(auto iter = result; iter; )
{
if(iter->next && iter->next->val == val)
iter->next = (iter->next->next ? iter->next->next : nullptr);
else
iter = iter->next;
}
return result->next;
}
};