กำหนดด้วย n โหนด และงานคือการพิมพ์ผลิตภัณฑ์ของโหนดหลักทั้งหมดในรายการที่เชื่อมโยง โหนดสำคัญคือโหนดที่จะมีค่าเฉพาะเป็นตำแหน่งที่นับ
ป้อนข้อมูล
10 20 30 40 50
ผลผลิต
4,00,000
คำอธิบาย − 10 อยู่ที่ค่าดัชนี 1 ซึ่งไม่ใช่ไพรม์ ดังนั้นจะถูกข้ามไป ย้ายไป 20 ด้วยค่าดัชนี 2 ซึ่งเป็นจำนวนเฉพาะจึงจะพิจารณา ในทำนองเดียวกัน 40 และ 50 อยู่ที่ตำแหน่งดัชนีหลัก
สินค้า − 20*40*50 =4,00,000
ในแผนภาพด้านบน โหนดสีแดงแสดงถึงโหนดที่สำคัญ
แนวทางที่ใช้ด้านล่างมีดังนี้
-
ใช้ตัวชี้ชั่วคราว สมมติว่า อุณหภูมิของโหนดประเภท
-
ตั้งค่าตัวชี้ชั่วคราวนี้เป็นโหนดแรกที่ชี้โดยตัวชี้ส่วนหัว
-
ย้าย temp ไปที่ temp→next และตรวจสอบว่าโหนดนั้นเป็นโหนดหลักหรือโหนดที่ไม่ใช่ไพรม์ หากโหนดเป็นไพร์มโหนด
-
DO Set product=product*(temp→data)
-
หากโหนดไม่เฉพาะมากกว่าย้ายไปยังโหนดถัดไป
-
พิมพ์ค่าสุดท้ายของตัวแปรผลิตภัณฑ์
อัลกอริทึม
Start Step 1 → create structure of a node to insert into a list struct node int data; node* next End Step 2 → declare function to insert a node in a list void push(node** head_ref, int data) Set node* newnode = (node*)malloc(sizeof(struct node)) Set newnode→data = data Set newnode→next = (*head_ref) Set (*head_ref) = newnode End Step 3 → Declare a function to check for prime or not bool isPrime(int data) IF data <= 1 return false End IF data <= 3 return true End IF data % 2 = 0 || data % 3 = 0 return false Loop For int i = 5 and i * i <= data and i = i + 6 IFdata % i = 0 || data % (i + 2) = 0 return false End End return true Step 4→ declare a function to calculate product void product(node* head_ref) set int product = 1 set node* ptr = head_ref While ptr != NULL IF (isPrime(ptr→data)) Set product *= ptr→data End Set ptr = ptr→next End Print product Step 5 → In main() Declare node* head = NULL Call push(&head, 10) Call push(&head, 2) Call product(head) Stop
ตัวอย่าง
#include <bits/stdc++.h> using namespace std; //structure of a node struct node{ int data; node* next; }; //function to insert a node void push(node** head_ref, int data){ node* newnode = (node*)malloc(sizeof(struct node)); newnode→data = data; newnode→next = (*head_ref); (*head_ref) = newnode; } // Function to check if a number is prime bool isPrime(int data){ if (data <= 1) return false; if (data <= 3) return true; if (data % 2 == 0 || data % 3 == 0) return false; for (int i = 5; i * i <= data; i = i + 6) if (data % i == 0 || data % (i + 2) == 0) return false; return true; } //function to find the product void product(node* head_ref){ int product = 1; node* ptr = head_ref; while (ptr != NULL){ if (isPrime(ptr→data)){ product *= ptr→data; } ptr = ptr→next; } cout << "Product of all the prime nodes of a linked list = " << product; } int main(){ node* head = NULL; push(&head, 10); push(&head, 2); push(&head, 7); push(&head, 6); push(&head, 85); product(head); return 0; }
ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
Product of all the prime nodes of a linked list = 14