Find modular node in a linked list in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a singly linked list LL and a number k. Our task is to Find modular node in a linked list.

Problem Description − we need to find the last node of the linked list for which the index is divisible by k i.e. i % k == 0.

Let’s take an example to understand the problem,

Input

ll = 3 -> 1 -> 9 -> 6 -> 8 -> 2, k = 4

Output

6

Explanation

The element 6 has index 4, which is divisible by 4.

Solution Approach

A simple solution to the problem is by creating a counter to count the elements of the linked list and store the modular node i.e. node for which i % k == 0, and update for all values satisfying the condition till n.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
struct Node {
   int data;
   Node* next;
};
Node* newNode(int data) {
   Node* new_node = new Node;
   new_node->data = data;
   new_node->next = NULL;
   return new_node;
}
Node* findModularNodeLL(Node* head, int k) {
   if (k <= 0 || head == NULL)
      return NULL;
   int i = 1;
   Node* modNode = NULL;
   for (Node* currNode = head; currNode != NULL; currNode =
      currNode->next) {
         if (i % k == 0)
            modNode = currNode;
            i++;
   }
   return modNode;
}
int main() {
   Node* head = newNode(3);
   head->next = newNode(1);
   head->next->next = newNode(9);
   head->next->next->next = newNode(6);
   head->next->next->next->next = newNode(8);
   head->next->next->next->next->next = newNode(2);
   int k = 4;
   Node* modularNode = findModularNodeLL(head, k);
   cout<<"The Modular node of linked list is ";
   if (modularNode != NULL)
      cout<<modularNode->data;
   else
   cout<<"Not found!";
   return 0;
}

Output

The Modular node of linked list is 6
raja
Published on 12-Mar-2021 07:35:02
Advertisements