In: Computer Science
C++
1. The function removeAt of the class arrayListType removes an
element from the list by shifting the elements ofthe list. However,
if the element to be removed is at the beginning ofthe list and the
list is fairly large, it could take a lot ofcomputer time. Because
the list elements are in no particular order, you could simply
remove the element by swapping the last element ofthe list with the
item to be removed and reducing the length of the list. Rewrite the
definition of the function removeAt using this technique.
2. The function remove of the class arrayListType removes only the
first occurrence of an element. Add the function removeAll to the
class arrayListType that would remove all occurrences of a given
element. Also, write the definition ofthe function removeAll and a
program to test this function.
From the textbook Data Structures using C++ by D. S. Malik
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 { // do not shift the list if we want to delete the first eleem if(location == 0) { list[0] = list[--length]; return; } for (int i = location; i < length - 1; i++) list[i] = list[i+1]; length--; } } //end removeAt template <class elemType> int arrayListType<elemType>::seqSearch(const elemType& item) const { int loc; bool found = false; for (loc = 0; loc < length; loc++) if (list[loc] == item) { found = true; break; } if (found) return loc; else return -1; } //end seqSearch template<class elemType> void arrayListType<elemType>::removeAll(const elemType& removeItem) { int loc; if (length == 0) cerr << "Cannot delete from an empty list." << endl; else { loc = seqSearch(removeItem); if(loc == -1) { cout << "The item to be deleted is not in the list." << endl; } while (loc != -1) { removeAt(loc); loc = seqSearch(removeItem); } } } //end remove
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.