https://leetcode.com/problems/linked-list-components/description/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int numComponents(ListNode* head, vector<int>& G) { unordered_set<int> s; for (auto i : G) s.insert(i); int res = 0; bool connected = false; while (head) { if (s.find(head->val) == s.end()) { connected = false; } else { if (!connected) { res++; connected = true; } } head = head->next; } return res; } };