ในปัญหานี้ เราได้รับรายการ LL และหมายเลข k ที่เชื่อมโยงเพียงอย่างเดียว งานของเราคือค้นหาโหนดโมดูลาร์ในรายการที่เชื่อมโยง
คำอธิบายปัญหา − เราต้องหาโหนดสุดท้ายของรายการที่เชื่อมโยงซึ่งดัชนีหารด้วย ki.e. i % k ==0.
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
ll = 3 -> 1 -> 9 -> 6 -> 8 -> 2, k = 4
ผลลัพธ์
6
คำอธิบาย
The element 6 has index 4, which is divisible by 4.
แนวทางการแก้ปัญหา
วิธีแก้ปัญหาอย่างง่ายคือการสร้างตัวนับเพื่อนับองค์ประกอบของรายการที่เชื่อมโยง และจัดเก็บโหนดโมดูลาร์ เช่น โหนดที่มี % k ==0 และอัปเดตสำหรับค่าทั้งหมดที่ตรงตามเงื่อนไขจนถึง n
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
ตัวอย่าง
#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;
} ผลลัพธ์
The Modular node of linked list is 6