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

在刷牛客网试题的时候发现和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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容