Struggling with this. Any help, code, or if anyone can shed some light to get me
ID: 3537725 • Letter: S
Question
Struggling with this. Any help, code, or if anyone can shed some light to get me on the right track then that would be awesome.
The function removeAt of the class arrayListType removes an element from the list by shifting the element of the list. However, if the element to be removed is at the beginning of the list and the list is fairly large, it could take a lot of computer time. Because the list elements are in no particular order, you could simple remove the element by swapping the last element of the list with the item to be removed and reducing the length of the list. Rewrite the definition of the function removeAt using this technique.
template <class elemType>
void arrayListType<elemType>::removeAt(int location)
{
if (location < 0 || location >= length)
cerr << "The location of the item to be removed "
<< "is out of range" << endl;
else
{
for (int i = location; i < length - 1; i++)
list[i] = list[i+1];
length--;
}
} //end removeAt
Explanation / Answer
template <class elemType>
void arrayListType<elemType>::removeAt(int location)
{
if (location < 0 || location >= length)
cerr << "The location of the item to be removed "<< "is out of range" << endl;
else
{
// SWAP WITH LAST ELEMENT AND REDUCE LENGTH.
elemType temp = list[location];
list[location] = list[length-1];
list[length-1] = temp;
length--;
}
} //end removeAt