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

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() {
int k = 4;