构造函数初始化链表
C++ 结构体可以有构造函数,提供构造函数可以使结点在创建时初始化。
构造函数可以像常规函数一样,使用默认形参来定义,为结点的后继指针提供一个默认的nullptr指针是很常见的。
代码如下:
struct listnode
{
string name;
listnode* next1;
//构造函数初始化结点
listnode(string name1, listnode* next2 = nullptr)
{
name = name1;
next1 = next2;
}
};
创建结点方式可以通过:
1 仅指定name部分,而后继指针设置为默认nullptr;
2 确定name部分和一个指向链表下一个结点的指针。
listnode *secondptr =new listnode("李洋");
listnode *head =new listnode("高富帅",secondptr);
代码改写形式
listnode *head = new listnode("李洋");
head = new listnode("高富帅",head);
从右到左评估,构造函数中使用head的旧值,然后从new运算符返回的地址将分配给head,成为它的新值。
#include<iostream>
using namespace std;
struct listnode
{
string name;
listnode* next1;
//构造函数初始化结点
listnode(string name1, listnode* next2 = nullptr)
{
name = name1;
next1 = next2;
}
};
int main()
{
listnode* secondptr = new listnode("高富帅");
listnode* head = new listnode("李洋", secondptr);
cout << "第一个名字是" << head->name << endl;
cout << "第二个名字是" << head->next1->name << endl;
return 0;
}
运行结果
参考: