File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
LinkedList-dataStructure/LL-implementation Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -191,6 +191,49 @@ class LinkedList
191
191
}
192
192
cout << endl;
193
193
}
194
+
195
+ int get (int index)
196
+ {
197
+ // Check whether node with this index exists
198
+ if (index < 0 || index >= this ->totalNodes )
199
+ {
200
+ cout << " [WARNING] Index out of bounds!" << endl;
201
+ return -1 ;
202
+ }
203
+
204
+ // Iterate over nodes until we reach the index-th node
205
+ Node *curr = this ->head ;
206
+ for (int i = 0 ; i < index; i++)
207
+ {
208
+ curr = curr->link ;
209
+ }
210
+
211
+ return curr->data ;
212
+ }
213
+
214
+ int find (int data)
215
+ {
216
+ // Iterate through all nodes
217
+ // In the worst case we don't find the node and reach the end of the list
218
+ Node *curr = this ->head ;
219
+ for (int i = 0 ; i < this ->totalNodes ; i++)
220
+ {
221
+ // Check whether we found the data, if so return the index at which it lies
222
+ if (curr->data == data)
223
+ {
224
+ return i;
225
+ } else if (curr->link == NULL )
226
+ {
227
+ break ;
228
+ }
229
+
230
+ curr = curr->link ;
231
+ }
232
+
233
+ // This means the loop terminated without finding the data
234
+ cout << " Could not find the node" << endl;
235
+ return -1 ;
236
+ }
194
237
};
195
238
196
239
int main ()
@@ -221,5 +264,11 @@ int main()
221
264
222
265
l.display ();
223
266
267
+ cout << " Get Node: 2" << endl;
268
+ cout << l.get (2 ) << endl;
269
+
270
+ cout << " Find Node 8:" << endl;
271
+ cout << l.find (8 ) << endl;
272
+
224
273
return 0 ;
225
274
}
You can’t perform that action at this time.
0 commit comments