How to test the written functions in the liked lists

I have written the following code for the linked list and now I want to test whether my function work correctly or not. Can anyone please show how to test those functions.

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
#include <iostream>


using namespace std;

class list {
private:
	struct node
	{
		int data;
		node *next;
	};
	node *head;
	node *tail;
public:
	list()
	{
		head = NULL;
		tail = NULL;
	}
	void createnode(int value)
	{
		node *temp = new node;
		temp->data = value;
		temp->next = NULL;
		if (head == NULL)
		{
			head = temp;
			tail = temp;
			temp = NULL;
		}
		else
		{
			tail->next = temp;
			tail = temp;
		}
	}
	void display()
	{
		node *temp = new node;
		temp = head;
		while (temp != NULL)
		{
			cout << temp->data << " ";
			temp = temp->next;
		}
	}
	bool pop_front(int val)
	{
		node *temp = new node;
		if (head == NULL)
		{
			return false;
		}
		else 
		{
			temp = head;
			head = head->next;
			delete temp;
		}
	}
	void push_back(int val)
	{
		node *last = new node;
		last->data = val;
		last->next = NULL;
		node *temp = new node;
		temp = head;
		if (temp == NULL)
		{
			head = last;
		}
		else
		{
			while (temp != NULL)
			{
				temp = temp->next;
			}
			temp->next = last;
		}
	}
};

int main()
{

	system("pause");
	return 0;
}
Last edited on
Just go ahead and test it. You're the one who knows what it's supposed to do. Push some things, pop some things, go crazy.

Although the pop function seems like maybe it's supposed to return the value? Possibly thorugh a reference?

And you're creating a lot of "new nodes" that are then just tossed away. It's as if you think you can't declare a pointer without allocating some new memory to it. Not so! If you want temp to point to head, just say node *temp = head.
Your class is really difficult to test.
For example if you create an empty list.
How can you check that it is empty?

Imagine you add a value 5 to it.
How can you check that the size of the list is 1?
How can you check that the first value is 5?

Is this homework?
Some comments on your code from reading it:

Lines 40, 50, and 64: you sometimes leak the memory allocated here.

Line 58. If this is the last item then you need to update tail too.

push_back() does the same thing that createnode() does, only slower and with bugs. It's slow because it walks through the list. It has bugs because it doesn't update tail. Perhaps createnode() is supposed to insert at the front?

You should have a destructor that deallocates all the nodes.
Topic archived. No new replies allowed.