删除C++中链表的M个节点后的N个节点?
让我们首先定义包含数据和指向下一个节点的指针的链表。
struct Node {
int data;
struct Node* next;
};然后我们创建我们的createList(Node**headPtr,intnew_data)函数,它接受一个指向Node的doublePointer和一个int值。在函数内部,我们将新创建的节点下一个指针分配给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,intM,intN)方法采用根节点以及M和N值。在里面,我们将Node*current分配给head并声明Node*t。
void deleteNnodesAfterM(Node *head, int M, int N){
Node *current = head, *t;
int nodeCount;在函数内部,我们有一个while循环,它在当前不指向null时运行。第一个for循环运行M次迭代。第一个for循环执行完毕后,当前指针指向链表中M之后的节点。然后为节点*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;最后,使用head指针的printList(Node*head)打印链表。
void printList(Node *head){
Node *temp = head;
while (temp != NULL){
cout<data<<" ";
temp = temp->next;
}
cout<示例
让我们看看下面的实现来删除链表的M个节点之后的N个节点-
#include
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<data<<" ";
temp = temp->next;
}
cout<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<输出结果上面的代码将产生以下输出-
M = 2 N = 2
原始链表:
14 12 10 8 6 4 2
删除后的链表:
14 12 6 4