# Linked List Components in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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 .

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){
ListNode *head = new ListNode(v);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
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;
int x = head->val;
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