Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách xóa N các nút sau M các nút trong danh sách được liên kết.
Hãy xem các bước để giải quyết vấn đề.
-
Viết một nút cấu trúc cho nút danh sách liên kết.
-
Khởi tạo danh sách được liên kết với dữ liệu giả.
-
Viết hàm xóa N nút sau M nút.
-
Khởi tạo một con trỏ bằng con trỏ đầu.
-
Lặp lại cho đến cuối danh sách được liên kết.
-
Di chuyển con trỏ đến nút tiếp theo cho đến M nút.
-
Xóa N nút
-
Di chuyển con trỏ đến nút tiếp theo
-
-
In danh sách liên kết
Ví dụ
Hãy xem mã.
#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;
} Đầu ra
Nếu bạn chạy đoạn mã trên, thì bạn sẽ nhận được kết quả sau.
Linked list before deletion: 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Null Linked list after deletion: 9 -> 6 -> 3 -> Null
Kết luận
Nếu bạn có bất kỳ câu hỏi nào trong hướng dẫn, hãy đề cập đến chúng trong phần bình luận.