get(int index) function linked lists
Nov 3, 2016 at 9:22pm UTC
Hello just want to find out if this code is right or can something change?
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
template <class T>
T LinkedList<T>::get(int index) const
{
Node<T>* nodePtr;
Node<T>* nodeReturn;
int count = 0;
nodePtr = head;
int number = size();
if (nodePtr == NULL)
{
throw "The list is empty." ;
}
else
{
if ((index >= 0) && (index <= number))
{
while (nodePtr != NULL)
{
if (count == index )
{
return nodePtr->data;
}
count++;
nodeReturn = nodePtr;
nodePtr = nodePtr->next;
}
}
else
{
throw "Invalid index." ;
}
}
}
Nov 4, 2016 at 2:13pm UTC
Line 5,26: What's the purpose of nodeReturn? It's not used.
Line 17: Assuming index is zero based, your upper bounds check is faulty. Let's assume size() is 5, then valid indexes would be 0-4 just like an array.
Topic archived. No new replies allowed.