C++根据数组创建单向链表

2019-09-25  本文已影响0人  Virtualer

在刷牛客网试题的时候发现和leetcode不一样的地方,leetcode只需要写核心算法,而牛客网需要写完整程序。对于链表这种题目当然避免不了要创建链表,那么就写下来链表的创建:

#include <iostream>
#include <vector>

using namespace std;

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

ListNode* CreateList(const vector<int> &vec) {
    if (vec.empty()) {
        return nullptr;
    }
    auto head = new ListNode(vec.at(0));
    ListNode* p = head;
    for (size_t i = 1; i < vec.size(); i++) {
        auto q = new ListNode(vec.at(i));
        p->next = q;
        p = p->next;
    }
    return head;
}

int main(int argc, char **argv) {
    vector<int> vec;
    vec.push_back(6);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);

    vec.shrink_to_fit();
    ListNode* head = CreateList(vec);
    while (head != nullptr) {
        cout << head->val << endl;
        head = head->next;
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读