题目大意:移除单向链表中所有值等于val的节点。
Problem:
https://leetcode.com/problems/remove-linked-list-elements/description/
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
Idea:
Use a dummy head
Solution:
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Running time: 30 ms class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode dummy{0}; dummy.next = head; ListNode* curr = &dummy; while (curr) { ListNode* next = curr->next; while (next && next->val == val) next = next->next; curr->next = next; curr = next; } return dummy.next; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment