C++ 链表基础

C++链表建立与打印

建立ListNode 结构体,与leetcode保存一致。
建立一个链表:1->2->3

先贴代码:


#include <iostream>
#include <vector>
#include <map>
#include <stack>

// #include "listnode.hpp"
using namespace std;

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

ListNode* createList1(ListNode* head,vector<int>& nums)
    {
        ListNode* n;//new node
        ListNode* t;//temporary node
        ListNode* h;//head node

        //first node
        n=new ListNode;//n points to a new node
        n->val=nums[0];
        t=n;//temporary node points to this node
        h=n;//head points to the first node
        
        for (int i=1;i<nums.size()-1;++i){
            n=new ListNode;
            n->val=nums[i];
            t->next=n;//the next part (of the node that t is pointing to) is what n is pointing to
            t=t->next;//t points to the next. t always points to temporarily new node.
        }

        //last node that points to null
        n=new ListNode;
        n->val=nums[nums.size()-1];
        t->next=n;
        n->next=NULL;

        return h;
    }

ListNode* createlist(vector<int>& nums){
    ListNode* h=new ListNode(-1);
    ListNode* t;
    t=h;

    for (int i=0;i<nums.size();++i){
        t->next=new ListNode(nums[i]);
        t=t->next;
    }
    return h->next;
}

void print_list(ListNode *head)
{
    while (head != nullptr)
    {
        std::cout << head->val << " ";
        head = head->next;
    }
    std::cout << std::endl;
}


int main()
{   
    vector<int> nums{5,7};
    ListNode* h=createlist(nums);
    print_list(h);
    return 0;
}


createlist1() 参考: https://www.youtube.com/watch?v=o5wJkJJpKtM.
在这里插入图片描述

createlist()为最终简化版。省去了n。

链表的创建

链表是一个动态的数据结构,每个节点都需要动态生成,生成方法有两种:
第一种使用new运算符(仅c++支持),上述代码采用的就是这种生成方法。

ListNode* n;
n=new ListNode;

delete n;

第二种使用malloc函数

ListNode* n;
n=(ListNode *)malloc(sizeof(ListNode));

free(p);

(大概是这样的吧…等以后会了再来填坑)
(待填坑2: 释放节点?)

new对初学者真的友好嘤嘤嘤

以上就是leetcode链表类问题本地调试所需代码了。
略~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值