I'm writing a Run-length encoding project using linked list. Is it possible next
to have value NULL
every time i create a Node
using new
?
I have
struct Node{
int x;
char c;
Node* next;
}
and
class RLElist{
private:
Node* startList;
public:
/*some member functions here*/
}
I need it to be NULL
so i can check if I've reached the last Node
of the list.
Yes. And as usual with something that is possible, in this case too there is more than single way to do it.
If you call a new
operator with value initilization semantics
Node* n = new Node();
than value initialization will be triggered and this will assign 0 value to each structure's data member if there is no user defined constructor in the structure.
You can also define a default constructor that will assign null to pointer ( and maybe do something else as well)
struct Node{
int x;
char c;
Node* next;
Node() : next( 0) {}
}
and use this as before
Node* n = new Node(); // your constructor will be called
And finally, you can initialize pointer in the place of it's declaration
struct Node{
int x;
char c;
Node* next = nullptr;
};
There are different options:
Add a constructor that value-initializes the pointer (which leaves it zero-initialized):
struct Node{
Node() : next() {} // you can also value initialize x and c if required.
int x;
char c;
Node* next;
};
Initialize at the point of declaration:
struct Node{
int x;
char c;
Node* next = nullptr;
};
Value-initialize the new
ed object:
node* Node = new Node(); // or new Node{};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.