ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีลบไพรม์โหนดทั้งหมดออกจากรายการที่เชื่อมโยงเพียงคนเดียว
มาดูขั้นตอนการแก้ปัญหากัน
-
เขียนโครงสร้างด้วยข้อมูลและตัวชี้ถัดไป
-
เขียนฟังก์ชันเพื่อแทรกโหนดลงในรายการที่เชื่อมโยงโดยลำพัง
-
เริ่มต้นรายการที่เชื่อมโยงเพียงอย่างเดียวด้วยข้อมูลจำลอง
-
วนซ้ำในรายการที่เชื่อมโยงเพียงอย่างเดียว ค้นหาว่าข้อมูลโหนดปัจจุบันเป็นข้อมูลเฉพาะหรือไม่
-
หากข้อมูลปัจจุบันไม่ใช่เฉพาะ ให้ลบโหนด
-
เขียนฟังก์ชันเพื่อลบโหนด พิจารณาสามกรณีต่อไปนี้ขณะลบโหนด
-
หากโหนดเป็นโหนดหลัก ให้ย้ายส่วนหัวไปยังโหนดถัดไป
-
หากโหนดเป็นโหนดกลาง ให้เชื่อมโยงโหนดถัดไปกับโหนดก่อนหน้า
-
หากโหนดเป็นโหนดปลาย ให้ลบลิงก์โหนดก่อนหน้าออก
-
ตัวอย่าง
มาดูโค้ดกันเลย
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void insertNode(Node** head_ref, int new_data) {
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
bool isPrime(int n) {
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
for (int i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
void deleteNonPrimeNodes(Node** head_ref) {
Node* ptr = *head_ref;
while (ptr != NULL && !isPrime(ptr->data)) {
Node *temp = ptr;
ptr = ptr->next;
delete(temp);
}
*head_ref = ptr;
if (ptr == NULL) {
return;
}
Node *curr = ptr->next;
while (curr != NULL) {
if (!isPrime(curr->data)) {
ptr->next = curr->next;
delete(curr);
curr = ptr->next;
}
else {
ptr = curr;
curr = curr->next;
}
}
}
void printLinkedList(Node* head) {
while (head != NULL) {
cout << head->data << " -> ";
head = head->next;
}
}
int main() {
Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
cout << "Linked List before deletion:" << endl;
printLinkedList(head);
deleteNonPrimeNodes(&head);
cout << "\nLinked List after deletion:" << endl;
printLinkedList(head);
} ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
Linked List before deletion: 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Linked List after deletion: 5 -> 3 -> 2 ->
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น