-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
99 lines (74 loc) · 1.49 KB
/
LinkedList.cpp
File metadata and controls
99 lines (74 loc) · 1.49 KB
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
95
96
97
98
99
/*
File Name: LinkedList.cpp
*/
#include <iostream>
#include "LinkedList.h"
using namespace std;
//Constructor
LinkedList::LinkedList()
{
head = nullptr;
}
//Destructor
LinkedList::~LinkedList()
{
Node* c = head;
while(c)
{
Node* t = c;
c = c->next;
delete t; //Deallocating memory of each node
}
head = nullptr;
}
//Inserts a new node with the given value
void LinkedList::insert(int v)
{
Node* insertValue = new Node(v);
if(!head)
{
head = insertValue;
return;
}
//Traverse to the last node
Node* temp = head;
while(temp->next)
{
temp = temp->next;
}
temp->next = insertValue; //Attached new node at the end
}
//Searches for a given value in the linked list
bool LinkedList::search(int v)
{
Node* searchValue = head;
while(searchValue)
{
if(searchValue->data == v)
{
return true; //Value found
}
searchValue = searchValue->next;
}
return false; //Value not found
}
//This prints all elements
void LinkedList::printList()
{
if(!head) //This is to check if the list is empty
{
cout << "The list is empty." << endl;
return;
}
Node* printValue = head;
while(printValue)
{
cout << printValue->data;
if(printValue->next)
{
cout << " -> "; //A print separator
}
printValue = printValue->next;
}
cout << endl;
}