Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Xóa N nút sau M nút trong danh sách liên kết C++


Định nghĩa cấu trúc nút danh sách liên kết:

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

Hàm createList thêm nút mới vào đầu danh sách:

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

Hàm deleteNnodesAfterM xóa N nút sau mỗi M nút:

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;
    }
}

Ví dụ hoàn chỉnh

#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 << "Danh sách gốc: " << endl;
    printList(head);
    deleteNnodesAfterM(head, M, N);
    cout << "Danh sách sau xóa: " << endl;
    printList(head);
    return 0;
}

Kết quả

M = 2 N = 2
Danh sách gốc:
14 12 10 8 6 4 2
Danh sách sau xóa:
14 12 6 4