链表.md 935 B

输入数组构建链表

#include <bits/stdc++.h>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;

    ListNode() : val(0), next(nullptr) {}

    ListNode(int x) : val(x), next(nullptr) {}
};

ListNode *buildListNode(vector<int> &nums) {
    ListNode *root = new ListNode();
    ListNode *cur = root;
    for (const auto &item: nums) {
        ListNode *node = new ListNode(item);
        cur->next = node;
        cur = node;
    }
    return root;
}

void printListNode(ListNode *root) {
    ListNode *cur = root->next;
    while (cur) {
        cout << cur->val << " ";
        cur = cur->next;
    }
    cout << endl;
}

int main() {
    string str;
    vector<int> nums;
    string num;
    cin >> str;
    stringstream ss(str);
    while (getline(ss, num, ',')) {
        nums.push_back(stoi(num));
    }
    ListNode *root = buildListNode(nums);
    printListNode(root);
    return 0;
}