Data Structures, Algorithms, & Applications in C++
Chapter 5, Exercise 5

The code is given below and in the file arrayListWithTrimToSize.h. Test code is included in arrayListWithTrimToSize.cpp.
template<class T>
class arrayListWithTrimToSize : public arrayList<T> 
{
   public:
      // constructor and destructor
      arrayListWithTrimToSize(int initialCapacity = 10)
           : arrayList<T> (initialCapacity) {}

      void trimToSize();
};

template<class T>
void arrayListWithTrimToSize<T>::trimToSize()
{// Make array length equal to max{listSize, 1}

   if (arrayLength == listSize)
      return;

   if (listSize == 0)
      {// replace with array of length 1
         delete [] element;
         element = new T[1];
         arrayLength  = 1;
         return;
      }


   // need to change array length and copy eleements into new array
   changeLength1D(element, listSize, listSize);
   arrayLength = listSize;
}

The complexity of this function is the same as that of changeLength1D, i.e., O(listSize).