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链表类问题本地调试所需代码了。
略~