Linked List Components in C++

C++Server Side ProgrammingProgramming

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
    • head := next of head
  • 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[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
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;
      while(head){
         int x = head->val;
         if(s.count(x)){
            if(!flag) ret++;
            flag = true;
         }else flag = false;
         head = head->next;
      }
      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
raja
Published on 04-May-2020 17:57:13
Advertisements