题目链接:https://leetcode.cn/problems/linked-list-components/
C++ 代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
int numComponents(ListNode* head, vector<int>& nums) {
unordered_set<int> set(nums.begin(), nums.end());
int res = 0, t = 0;
for (auto p = head; p != nullptr; p = p->next) {
if (set.count(p->val)) {
t++;
} else {
if (t > 0) {
res++;
t = 0;
}
}
}
if (t > 0) res++;
return res;
}
};