在 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP