在 C++ 中刪除連結串列中 M 個節點後的 N 個節點?


讓我們首先定義包含資料和指向下一個節點的指標的連結串列。

struct Node {
   int data;
   struct Node* next;
};

然後,我們建立 `createList(Node ** headPtr, int new_data)` 函式,它接受指向 Node 的雙指標和一個整數值。在函式內部,我們將新建立的節點的 next 指標賦值給 headptr,然後將 headptr 賦值給新建立的節點。

void createList(Node ** headPtr, int new_data){
   Node* newNode = new Node();
   newNode->data = new_data;
   newNode->next = (*headPtr);
   (*headPtr) = newNode;
}

`deleteNnodesAfterM(Node *head, int M, int N)` 方法接受根節點以及 M 和 N 值。在內部,我們將 Node* current 賦值給 head,並宣告 Node *t。

void deleteNnodesAfterM(Node *head, int M, int N){
   Node *current = head, *t;
   int nodeCount;

在函式內部,我們有一個 while 迴圈,當 current 不指向 null 時執行。第一個 for 迴圈執行 M 次迭代。第一個 for 迴圈執行完畢後,**current** 指標指向連結串列中 M 之後的節點。然後將 Node *t 賦值為 current->next,這是要刪除的第一個值。

while (current){
   for (nodeCount = 1; nodeCount < M && current!= NULL; nodeCount++)
   current = current->next;
   if (current == NULL)
      return;
   t = current->next;

第二個 for 迴圈執行 N 次迭代,並從起始位置釋放 N 個節點。然後將 current->next 賦值給 t,t 成為我們的當前節點。

for (nodeCount = 1; nodeCount<=N && t!= NULL; nodeCount++){
   Node *temp = t;
   t = t->next;
   free(temp);
}
current->next = t;
current = t;

最後,`printList(Node *head)` 接受 head 指標並列印連結串列。

void printList(Node *head){
   Node *temp = head;
   while (temp != NULL){
      cout<<temp->data<<" ";
      temp = temp->next;
   }
   cout<<endl;
}

示例

讓我們來看一下以下實現,以刪除連結串列中 M 個節點後的 N 個節點:

線上演示

#include <iostream>
using namespace std;
struct Node{
   int data;
   Node *next;
};
void createList(Node ** headPtr, int new_data){
   Node* newNode = new Node();
   newNode->data = new_data;
   newNode->next = (*headPtr);
   (*headPtr) = newNode;
}
void printList(Node *head){
   Node *temp = head;
   while (temp != NULL){
      cout<<temp->data<<" ";
      temp = temp->next;
   }
   cout<<endl;
}
void deleteNnodesAfterM(Node *head, int M, int N){
   Node *current = head, *t;
   int nodeCount;
   while (current){
      for (nodeCount = 1; nodeCount < M && current!= NULL; nodeCount++)
      current = current->next;
      if (current == NULL)
      return;
      t = current->next;
      for (nodeCount = 1; nodeCount<=N && t!= NULL; nodeCount++){
         Node *temp = t;
         t = t->next;
         free(temp);
      }
      current->next = t;
      current = t;
   }
}
int main(){
   Node* head = NULL;
   int M=2, N=2;
   createList(&head, 2);
   createList(&head, 4);
   createList(&head, 6);
   createList(&head, 8);
   createList(&head, 10);
   createList(&head, 12);
   createList(&head, 14);
   cout << "M = " << M<< " N = " << N<<endl;
   cout<< "Original linked list :"<<endl;
   printList(head);
   deleteNnodesAfterM(head, M, N);
   cout<<"Linked list after deletion :"<<endl;
   printList(head);
   return 0;
}

輸出

以上程式碼將產生以下輸出:

M = 2 N = 2

Original linked list :
14 12 10 8 6 4 2

Linked list after deletion :
14 12 6 4

更新於:2021年1月16日

168 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.