Data Structures, Algorithms, & Applications in C++
Chapter 5, Exercise 23
The code is given below and in the file
arrayListWithLeftShift.h. Test code is
included in arrayListWithLeftShift.cpp.
template<class T>
class arrayListWithLeftShift : public arrayList<T>
{
public:
// constructor and destructor
arrayListWithLeftShift(int initialCapacity = 10)
: arrayList<T> (initialCapacity) {}
void leftShift(int theAmount);
};
template<class T>
void arrayListWithLeftShift<T>::leftShift(int theAmount)
{// Left shift by i elements.
if (theAmount <= 0)
return;
// could throw exception when i < 0 or do a right shift by i
int newSize = 0;
if (theAmount < listSize)
{// list is not empty after the shift
newSize = listSize - theAmount;
// left shift elements with higher index >= i
copy(element + theAmount, element + listSize, element);
}
// destroy uneeded elements
for (int i = newSize; i < listSize; i++)
element[i].~T();
listSize = newSize;
}
The complexity of the method is O(listSize).