在C ++程序的链接列表的M个节点之后删除N个节点

在本教程中,我们将学习如何在链接列表中的M个节点之后删除N个节点。

让我们看看解决问题的步骤。

  • 为链接列表节点编写一个结构节点。

  • 用伪数据初始化链表。

  • 编写一个删除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) {
      // 跳过M个节点
      for (count = 1; count < M && current!= NULL; count++) {
         current = current->next;
      }
      // 链表的末尾
      if (current == NULL) {
         return;
      }
      // 在M个节点之后删除N个节点
      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 << "删除前的链接列表: ";
   printLinkedList(head);
   deleteNNodesAfterMNodes(head, M, N);
   cout << "删除后的链接列表: ";
   printLinkedList(head);
   return 0;
}
输出结果

如果运行上面的代码,则将得到以下结果。

删除前的链接列表: 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Null
删除后的链接列表: 9 -> 6 -> 3 -> Null

结论