Skip to content

Commit 7163983

Browse files
authored
Merge pull request #30 from ybrenning/master
Added LList access methods (#29)
2 parents 9060c14 + d5eb51d commit 7163983

File tree

1 file changed

+49
-0
lines changed
  • LinkedList-dataStructure/LL-implementation

1 file changed

+49
-0
lines changed

LinkedList-dataStructure/LL-implementation/main.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,49 @@ class LinkedList
191191
}
192192
cout << endl;
193193
}
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+
}
194237
};
195238

196239
int main()
@@ -221,5 +264,11 @@ int main()
221264

222265
l.display();
223266

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+
224273
return 0;
225274
}

0 commit comments

Comments
 (0)