使用自定义链表或使用STL之list完成下面案例

题目描述

输入n个正整数,建立单链表L,要求链表中每个结点之后所有结点的数据域值都不是该结点数据域值的倍数,输出链表L中的结点个数及各个数据域值,然后将链表L逆置并输出。 输入格式: 首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。对于每组测试数据,输入2行,第一行输入数据个数n,第二行输入n个正整数。 输出格式: 对于每组测试,输出3行,第一行是链表L的数据结点个数,第二行是链表L中各个结点的数据域值,第三行是链表L逆置后的结果。每行的每两个数据之间留一个空格。

源代码

#include <iostream>
#include <list>
using namespace std;

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

Node* createList(int n) {
    Node* head = nullptr;
    Node* tail = nullptr;
    for (int i = 0; i < n; i++) {
        int num;
        cin >> num;
        Node* newNode = new Node();
        newNode->data = num;
        newNode->next = nullptr;
        if (head == nullptr) {
            head = newNode;
            tail = newNode;
        } else {
            tail->next = newNode;
            tail = newNode;
        }
    }
    return head;
}

int countNodes(Node* head) {
    int count = 0;
    Node* curr = head;
    while (curr != nullptr) {
        count++;
        curr = curr->next;
    }
    return count;
}

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

void reverseList(Node*& head) {
    Node* prev = nullptr;
    Node* curr = head;
    while (curr != nullptr) {
        Node* next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    head = prev;
}

void deleteList(Node*& head) {
    Node* curr = head;
    while (curr != nullptr) {
        Node* temp = curr;
        curr = curr->next;
        delete temp;
    }
    head = nullptr;
}

int main() {
    int T;
    cin >> T;

    for (int i = 0; i < T; i++) {
        int n;
        cin >> n;

        Node* head = createList(n);

        // 遍历链表,删除结点后面的倍数结点
        Node* curr = head;
        while (curr != nullptr) {
            Node* temp = curr->next;
            Node* prev = curr;
            while (temp != nullptr) {
                if (temp->data % curr->data == 0) {
                    prev->next = temp->next;
                    delete temp;
                    temp = prev->next;
                } else {
                    prev = temp;
                    temp = temp->next;
                }
            }
            curr = curr->next;
        }

        int nodeCount = countNodes(head);

        cout << nodeCount << endl;
        printList(head);

        reverseList(head);

        printList(head);

        deleteList(head);
    }

    return 0;
}

输入示例:

2
5
1 2 3 4 5
6
2 4 6 8 10 12

输出示例:

5
1 2 3 4 5
5 4 3 2 1
6
2 4 6 8 10 12
12 10 8 6 4 2

该代码首先读取测试数据的组数T,然后对于每组测试数据,读取数据个数n和n个正整数。接下来,根据输入的数据创建链表,并遍历链表删除结点后面的倍数结点。然后输出链表的结点个数和各个结点的数据域值。接着逆置链表并输出逆置后的结果。最后释放链表的内存。

© 版权声明
THE END
喜欢就支持一下吧
点赞11赞赏 分享