Linked List not printing the last element

Hi guys,
OK, I know the answer to this problem is going to be obvious - but i can't see it for some reason.
I wrote a class for a linked list. I added three elements. only 2 get printed.
The problem is in the print() function - but i can't see what it is.

I'd appreciate your help.

Also, if you have any suggestions for the code - i'd really appreciate those too :)

thanks!

Code
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
#include <string>
#include <iostream>
using namespace std;

struct Node
{
	string data;
	struct Node *next;
};

class LinkedList
{
	public:
	   LinkedList();
	   ~LinkedList();
	   void add(string word);
	   void remove();
	   void print();
	private:
	   int count;
	   Node *head;
	   Node *tail;
};

LinkedList::LinkedList()
{
	head = NULL;
	tail = NULL;
	count = 0;
}

void LinkedList::add(string word)
{
	Node *node = new Node();
	node->data = word;
	this->count++;
	if(head == NULL)
	{
		head = node;
		tail = node;
		tail->next = NULL;
	}
	else
	{
		tail->next = node;
		tail = node;
		node->next = NULL;
	}	
}

void LinkedList::remove()
{
	Node *iterator = head; //start from the beginning
	while (iterator->next != NULL)
		iterator = iterator->next; //this will land it on tail.
	delete this->tail;
	this->tail = iterator;
	this->tail->next = NULL;
	this->count --;
}

void LinkedList::print()
{
	Node *iterator = new Node();
	iterator = head;
	int count = 1;
	while(iterator->next != NULL)
	{
		cout<<count<<". "<<iterator->data<<endl;
		iterator = iterator->next;
		count++;
	}
	cout<<"Total data stored in list: "<<this->count<<endl;	
}

LinkedList::~LinkedList()
{
	delete this;
}

int main()
{
	LinkedList *list = new LinkedList();
	list->add("bird");
	list->add("bird's the word");
	list->add("ssssuuuuuurrrrfffffiiiiiinnnnnnggggg");
	list->print();
	list->remove();
	list->print();
	return 0;	
}


Output

1. bird
2. bird's the word
Total data stored in list: 3

1. bird
2. bird's the word
Total data stored in list: 2

Try changing

while(iterator->next != NULL)

To while(iterator != NULL)

You know that you are in the last element when iterator->next == NULL, but in your loop (line 67) the condition will be false for the last element thus it won't enter the loop.

Edit: Meh <_< Either my typing is really slow or there are a few ninjas around here.
Last edited on
@Zeillinger: I feel like kicking myself. I even wrote that in the draft I made before I started coding. I can't believe it was that obvious. Thanks a bucnh for the quick reply! :)
BTW: is LinkedList::~LinkedList(){delete this;} a suitable destructor for linked Lists.
Last edited on
Topic archived. No new replies allowed.