#include<iostream>
usingnamespace std;
class DoublyLinkedList
{
protected:
struct ListNode
{
int value;
ListNode *next;
ListNode *prev;
ListNode(int value1, ListNode *prev1)//, ListNode *next1 = NULL)
{
value = value1;
if(prev1 == NULL)
{
next = prev1;
prev = prev1;
}
else
{
next = prev1->next;
prev = prev1;
}
}
};
ListNode *head; //list head pointer
public:
DoublyLinkedList() //constructor
{
head = NULL;
}
~DoublyLinkedList(); //destructor
void add(int value);
void displayList();
};
void DoublyLinkedList::add(int value)
{
if (head == NULL)
{
head = new ListNode(value, head);
}
else
{
/*The list is not empty. So use
nodePtr to traverse the list */
ListNode *nodePtr = head;
while(nodePtr->next != NULL)
nodePtr = nodePtr->next;
/*nodePtr->next is NULL so nodePtr points to the
last node. Create a new node and put it after the
last node.*/
nodePtr->next = new ListNode(value, nodePtr);
}
}
void DoublyLinkedList::displayList()
{
//Start at the head of the list
ListNode *nodePtr = head;
while(nodePtr)
{
cout<<nodePtr->value<< ", ";
nodePtr = nodePtr->next;
}
}
DoublyLinkedList::~DoublyLinkedList()
{
ListNode *nodePtr = head;
while(nodePtr != NULL)
{
//garbage keeps track of node to be deleted
ListNode *garbage = nodePtr;
//move on to the next node, if any
nodePtr = nodePtr->next;
//delete "garbage" node
delete garbage;
}
}
But what I do not know is if the last node's next, and the first node's prev member variables are pointing to NULL. I am pretty sure they are. Could I get someone else's insight? Knowing I am correctly coding doubly-linked lists will assure me that when I create other member functions, they will be correct.
One way to check is to modify your displayList function to test if the prev and next are NULL. Obviously you last next points to NULL, otherwise you would not end the loop.
Also, look at lines 21 and 26. You execute the same command in either case, so there is no point in having it inside the if else statement. Take it outside.