首页 > 解决方案 > 如何在 C++ 中使用 for 循环声明 n 个链表?

问题描述

我试图从用户那里得到 n ,这将决定链表的数量。我将向这些链表添加元素,创建链表向量并将向量传递给 UDF。我无法使用 for 循环本身声明 n 个链表。

标签: c++linked-list

解决方案


根据我对问题的理解,也许这对你有用。

只需初始化一个向量并继续在其中推送新列表。

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* next;
    
    Node (int data) {
        this->data = data;
        this->next = nullptr;
    }
};

vector<Node*> createLists(int n) {
    vector<Node*> lists;
    for (int i = 1; i <= n; i++) {
        Node* node = new Node(100 + i);
        lists.push_back(node);
    }
    return lists;
}


int main() {
    int n;
    cin >> n;
    vector<Node*> lists = createLists(n);
    return 0;
}

您可以创建一种insertElement方法来在向量中的每个链表中添加项目


推荐阅读