ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีลบ N โหนดหลัง M โหนดในรายการที่เชื่อมโยง
มาดูขั้นตอนการแก้ปัญหากัน
-
เขียน struct Node สำหรับโหนดรายการที่เชื่อมโยง
-
เริ่มต้นรายการที่เชื่อมโยงด้วยข้อมูลจำลอง
-
เขียนฟังก์ชันเพื่อลบโหนด N หลังโหนด M
-
เริ่มต้นตัวชี้ด้วยตัวชี้ส่วนหัว
-
วนซ้ำจนจบรายการที่เชื่อมโยง
-
ย้ายตัวชี้ไปยังโหนดถัดไปจนถึงโหนด M
-
ลบโหนด N
-
ย้ายตัวชี้ไปยังโหนดถัดไป
-
-
พิมพ์รายการที่เชื่อมโยง
ตัวอย่าง
มาดูโค้ดกันเลย
#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;
}
void printLinkedList(Node *head) {
Node *temp = head;
while (temp != NULL) {
cout<< temp->data << " -> ";
temp = temp->next;
}
cout << "Null" << endl;
}
void deleteNNodesAfterMNodes(Node *head, int M, int N) {
Node *current = head, *temp;
int count;
while (current) {
// skip M nodes
for (count = 1; count < M && current!= NULL; count++) {
current = current->next;
}
// end of the linked list
if (current == NULL) {
return;
}
// deleting N nodes after M nodes
temp = current->next;
for (count = 1; count <= N && temp != NULL; count++) {
Node *deletingNode = temp;
temp = temp->next;
free(deletingNode);
}
current->next = temp;
current = temp;
}
}
int main() {
Node* head = NULL;
int M = 1, N = 2;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
insertNode(&head, 7);
insertNode(&head, 8);
insertNode(&head, 9);
cout << "Linked list before deletion: ";
printLinkedList(head);
deleteNNodesAfterMNodes(head, M, N);
cout << "Linked list after deletion: ";
printLinkedList(head);
return 0;
} ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
Linked list before deletion: 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Null Linked list after deletion: 9 -> 6 -> 3 -> Null
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น