I'm trying to create a few nodes for a doubly linked-list and print them out. So I create my dnode class:
template <typename T>
class dnode
{
public:
T nodeValue;
dnode<T> *prev;
dnode<T> *next;
dnode() : prev(this), next(this) {}
dnode(const T& item, dnode<T> *prevNode = NULL, dnode<T> *nextNode = NULL) :
nodeValue(item), prev(prevNode), next(nextNode) {}
};
Then I have my writeList function:
template <typename T>
void writeDLinkedList(dnode<T>* header, const string& seperator = " ")
{
dnode<T> *p = header->next;
while (p != header)
{
cout << p->nodeValue << seperator;
p = p->next;
}
cout << endl << endl;
}
In main, I create a header pointer and two nodes, using the constuctor to assign the previous and next nodes in the circular list:
dnode<int> *header, *one, *two;
header = new dnode<int>(0, two, one);
one = new dnode<int> (10, header, two);
two = new dnode<int> (25, one, header);
writeDLinkedList(header);
When I call writeDLinkedList, I get a segmentation fault. I was confused by this, so I eventually tried to output each node value individually to see if the pointers were working correctly. It turns out they weren't. Instead, I have to do this to get the print function working correctly:
header = new dnode<int>;
one = new dnode<int> (10);
two = new dnode<int> (25);
header->next = one;
one->next = two;
two->next = header;
writeDLinkedList(header);
I want to know why my constructor isn't working the way it should. Is it the initialization list?
prevandnextshould be initialized toNULL, not tothis. Checks for valid nodes should then be updated to look forNULLwhile looping.