问题描述
在C++
数据结构中,结点定义写法:
// Definition for singly-linked list.
struct SinglyListNode {
int val;
SinglyListNode *next;
SinglyListNode(int x) : val(x), next(NULL) {}
};
在C
数据结构中,结点定义写法:
typedef struct linkednode
{
int val;
struct linkednode * next;
} snode, *ptr;
不知道代码C++定义中SinglyListNode(int x) : val(x), next(NULL) {}
是什么意思?
2020-7-24:
SinglyListNode(int x) : val(x), next(NULL) {}
是构造函数,构造函数后面有一个冒号:
,冒号后面跟了val(x)
,构造体的内部是空的{}
。冒号后面的就是初始化列表,在初始化列表里面,可以为每一个成员变量指定一个初始值,比如这里的val(x)
,就是把x
初始化给val
。
分析与结论
2.1 结论
SinglyListNode(int x) : val(x), next(NULL) {}
是构造函数
,构造函数
的作用是用于初始化类对象的成员。
在这里就是,给结点初始化一个头结点。
2.2 测试代码
#include <iostream>
using namespace std;
struct SinglyListNode {
int val;
SinglyListNode * next;
SinglyListNode(int x) : val(x), next(NULL) {}
};
void outlinkedlist(SinglyListNode * p);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
SinglyListNode * Ha; //定义一个链表结点指针
Ha = new SinglyListNode(5); //新建一个结点,数据内容为5,next为NULL。Ha指向该结点
outlinkedlist(Ha);
return 0;
}
void outlinkedlist(SinglyListNode * p)
{
cout << "The List is: " << endl;
while (p != NULL)
{
cout << p->val << "->";
p = p->next;
}
cout << "NULL" << endl;
}
结果
参考资料
[1] CSDN论坛: https://bbs.csdn.net/topics/390806135