# Linked List Components in C++

Suppose we have given a head; this is the head node of a linked list containing unique integer values. Now we are also given the list G, a subset of the values in the linked list. We have to find the number of connected components in G, where two values are connected if they appear consecutively in the linked list. So if the list is like [0,1,2,3] and G = [0,1,3], then output will be 2, as 0 and 1 are connected, so there are two lists [0,1] and [3].

To solve this, we will follow these steps −

• ret := 0, make a set s, and insert all elements of G into s
• flag := false
• while head is not null
• x := value of head
• if s has x, then
• if flag is false, increase ret by 1
• flag := true
• otherwise set flag := false
• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
class Solution {
public:
int numComponents(ListNode* head, vector<int>& G) {
int ret = 0;
set < int > s;
for(int i = 0; i < G.size(); i++)s.insert(G[i]);
bool flag = false;
if(s.count(x)){
if(!flag) ret++;
flag = true;
}else flag = false;
}
return ret;
}
};
main(){
vector<int> v1 = {0,1,2,3};
vector<int> v2 = {0,1,3};
ListNode *h1 = make_list(v1);
Solution ob;
cout << (ob.numComponents(h1, v2));
}

## Input

[0,1,2,3]
[0,1,3]

## Output

2

Updated on: 04-May-2020

235 Views