在 C++ 程式中刪除連結串列中 M 個節點之後的 N 個節點
在本教程中,我們將學習如何在連結串列中刪除 **N** 個節點之後的 **M** 個節點。
讓我們看看解決問題的步驟。
為連結串列節點編寫一個結構體 Node。
使用虛擬資料初始化連結串列。
編寫一個函式來刪除 M 個節點之後的 N 個節點。
用頭指標初始化一個指標。
迭代到連結串列的末尾。
將指標移動到下一個節點,直到 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
結論
如果您在本教程中有任何疑問,請在評論區中提出。
廣告