Doubly-Linked Lists

I am writing my own doubly-linked list class. I was wondering if my code looks correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
 #include<iostream>
using namespace 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;
	}
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include"DoublyLinkedList.h"
#include<iostream>
using namespace std;

int main()
{
	DoublyLinkedList dl1;
	dl1.add(5);
	dl1.add(6);
	dl1.add(7);
	dl1.displayList();

	return 0;
}


What I do know is that i get the correct output:
5,6,7,

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.
Topic archived. No new replies allowed.