以下例子的 head 头部,不用来保存有效数据
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
};
//初始化列表
ListNode* InitList(ListNode *head, int n)
{
int a=0;
ListNode *p, *s;
head = (ListNode*)malloc(sizeof(ListNode));
head->next = nullptr;
p=head;
for (int i=0; i<n; i++)
{
s=(ListNode*)malloc(sizeof(ListNode));
a=a+1; //可以用输入的方式,这里是直接演示的自加
s->val=a;
s->next = nullptr;
p->next = s;
p=s;
}
return head;
}
//打印链表
void Print(ListNode *head)
{
ListNode *p;
p=head->next;
while(p!=nullptr){
cout<<p->val;
p=p->next;
}
}
//主函数
int main()
{
ListNode *head;
head = InitList(head, 5);
Print(head);
return 0;
}
结果
主要用到了动态申请内存,malloc(),以后在链表删除等还会用到free()等函数。
//初学者版本
struct ListNode {
int val;
ListNode *next;
};
//改进版本
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) {}
};
构造函数,结构体和类是类似的?
不再用molloc的方式,而是使用对象new一个的方式
//初学者
head = (ListNode*)malloc(sizeof(ListNode));
s=(ListNode*)malloc(sizeof(ListNode));
s->val=具体值;
s->next = nullptr;
//改进
head = new ListNode(); //调用无参构造函数ListNode()
s = new ListNode(具体一个整数); //调用了一个参数的构造函数 ListNode(int x)
代码,给了连个链表的具体值
#include <iostream>
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* InitList(ListNode *head, int *n, int length)
{
int a=0;
ListNode *p, *s;
head = new ListNode(); //不是malloc()了
p=head;
for (int i=0; i<=length; i++)
{
s = new ListNode(n[i]); //不是malloc()了
p->next = s;
p=s;
}
return head;
}
//打印链表
void Print(ListNode *head)
{
ListNode *p;
p=head->next;
while(p!=nullptr){
cout<<p->val;
p=p->next;
}
cout<<endl;
}
int main()
{
ListNode *l1,*l2;
int a[]={2,4,3}; //链表节点具体值,这里就不一一输入,直接用数组来代替
int b[]={5,6,4};
l1 = InitList(l1, a, sizeof(a)/sizeof(a[0]));
l2 = InitList(l2,b, sizeof(b)/sizeof(b[1]));
Print(l2);
Print(l1);
return 0;
}