-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.cpp
141 lines (112 loc) · 2.28 KB
/
LinkedList.cpp
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <iostream>
using namespace std;
class Node{
public:
double data; //data of the node
Node *next; //pointer to next node
};
class List{
public:
List(void){
head =NULL; //constructor
}
~List(void); //destructor
bool IsEmpty(){
return head == NULL;
}
Node* InsertNode(int index, double data);
int FindNode(double data);
int DeleteNode(double data);
void DisplayList(void);
private:
Node *head;
};
Node* List::InsertNode(int index, double data){
if(index < 0) return NULL;
int currIndex = 1;
Node* currNode = head;
while(currNode && index > currIndex){
currNode = currNode->next;
currIndex++;
}
if(index > 0 && currNode == NULL) return NULL;
Node* newNode = new Node;
newNode->data = data;
if(index == 0){
newNode->next = head;
head = newNode;
}
else{
newNode->next = currNode->next;
currNode->next = newNode;
}
return newNode;
}
int List::FindNode(double data){
Node* currNode = head;
int currIndex = 1;
while(currNode && currNode->data != data){
currNode = currNode->next;
currIndex++;
}
if(currNode) return currIndex;
return 0;
}
int List::DeleteNode(double data){
Node* prevNode = NULL;
Node* currNode = head;
int currIndex = 1;
while(currNode && currNode->data != data){
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if(currNode){
if(prevNode){
prevNode->next = currNode->next;
delete currNode;
}
else{
head = currNode->next;
delete currNode;
}
return currIndex;
}
return 0;
}
void List::DisplayList(){
int count = 0;
Node* currNode = head;
while(currNode != NULL){
cout << currNode->data << endl;
currNode = currNode->next;
count++;
}
cout << "Number of nodes int the list: " << count << endl;
}
List::~List(void){
Node* currNode = head, *nextNode = NULL;
while(currNode != NULL){
nextNode = currNode->next;
delete currNode;
currNode = nextNode;
}
}
int main(){
List list;
list.InsertNode(0, 7.0);
list.InsertNode(1, 5.6);
list.InsertNode(0,3.2);
list.DisplayList();
if(list.FindNode(5.6) > 0)
cout << "5.6 found!" << endl;
else
cout << "5.6 not found!" <<endl;
if(list.FindNode(4.0) > 0)
cout << "4.0 found" << endl;
else
cout << "4.0 not found" << endl;
list.DeleteNode(3.2);
list.DisplayList();
return 0;
}