Return nothing in Linked List

Nov 4, 2019 at 5:26pm
Hello,
I wrote Linked List. I want to return nothing in the Delete method when Linked List is empty. How can fix my code? now when the linked list is empty, the program returns a strange number.


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

struct Node{
	int Data;
	 Node* Next;
};
class LinkedList {

private:
	Node* Head = NULL;
	Node* Tail = NULL;
	Node* temp = NULL;
public:
	void Create()
	{

	}

	void Setup(int Data)
	{
		temp = new Node;
		temp->Data = Data;
		temp->Next = NULL;
		if (Head == NULL)
		{
			Head = temp;
			Tail = temp;
		}
		else
		{
			Tail->Next = temp;
			Tail = temp;
		}
		cout << "Insert : " << Data << endl;
	}

	int Delete()
	{
		if (Head != NULL)
		{
			temp = Head;
			Head = Head->Next;
			return temp->Data;
		}
		else
		{
			cout << " List is Empty \n";
		}
	}
};

int main()
{
	LinkedList ls;
	ls.Setup(15);
	ls.Setup(1);
	ls.Setup(5);
	ls.Setup(9);
	cout<<" Deleted Item is: "<<ls.Delete()<<endl;
	ls.Setup(4);
	ls.Setup(545);
	cout << " Deleted Item is: " << ls.Delete() << endl;
	ls.Setup(0);
	ls.Setup(-19);
	cout << " Deleted Item is: " << ls.Delete() << endl;
	cout << " Deleted Item is: " << ls.Delete() << endl;	
	cout << " Deleted Item is: " << ls.Delete() << endl;
	cout << " Deleted Item is: " << ls.Delete() << endl;
	cout << " Deleted Item is: " << ls.Delete() << endl;
	cout << " Deleted Item is: " << ls.Delete() << endl;	
	cout << " Deleted Item is: " << ls.Delete() << endl;	
	cout << " Deleted Item is: " << ls.Delete() << endl;


}
Nov 4, 2019 at 6:25pm
Is there a value you could use that would safely indicate that the list was empty, rather than being the value of Data in the deleted node? Say, zero? Or a negative value? Or INT_MAX? Or are those numbers that could be valid values of Data?

If not, you could try using boost::optional, although that's quite advanced for someone posting in the Beginners forum :)

Last edited on Nov 4, 2019 at 6:27pm
Nov 4, 2019 at 6:26pm
delete is not deleting, it is doing a search. Perhaps a translation problem, but this is very confusing due to the name vs action done.

that aside you can't return 'nothing' to an integer. You can try a sentinel, or you can return some sort of structure that contains a 'not found invalid' boolean, or you can return a pointer to the data and set that to null if there is no data (this is a form of nothing).
Last edited on Nov 4, 2019 at 6:28pm
Nov 4, 2019 at 6:29pm
You probably need to return something from your "delete" function when head is not a nullptr.

Topic archived. No new replies allowed.