我正在使用链表编写游程编码项目。每次我使用 new
创建 Node
时,next
是否有可能具有值 NULL
?
我有
struct Node{
int x;
char c;
Node* next;
}
和
class RLElist{
private:
Node* startList;
public:
/*some member functions here*/
}
我需要它为 NULL
,这样我就可以检查我是否到达了列表的最后一个 Node
。
最佳答案
有不同的选择:
添加一个对指针进行值初始化的构造函数(使其保持零初始化):
struct Node{
Node() : next() {} // you can also value initialize x and c if required.
int x;
char c;
Node* next;
};
在声明点初始化:
struct Node{
int x;
char c;
Node* next = nullptr;
};
值初始化新
对象:
node* Node = new Node(); // or new Node{};
关于c++如何在创建新结构时将NULL值分配给成员指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24109460/