So I have an assignment to redefine an array-based Stack push() function. The problem itself sounds like it totally defeats the purpose of a stack, but this is what I have been assigned:

Rewrite the push function so 'myTop' is always 0 instead of one more than the index of the last element. Now determine the worst-case complexity of the function (for Big O notation).

Not so worried about finding the worst-case complexity, but I'm having trouble redefining the following push() function to have myTop at 0 and be able to add elements on top of myTop.

Any tips?

void Stack::push(const StackElement & value)
{
   if (myTop < STACK_CAPACITY - 1) 
   { 
      ++myTop;
      myArray[myTop] = value;
   }
   else
   {
      cerr << "*** Stack full -- can't add new value ***\n"
              "Must increase value of STACK_CAPACITY in Stack.h\n";
      exit(1);
   }
}

Do you know how an insertion operation works?

What the assignment requires is that you verify there is sufficient space in the stack, then perform an insertion at element 0 rather than storing it to the first available legal space within the array.

Something like this:

//assume the following variables:
//elementCount     - the current "size" of the stack
//capacity         - the maximum number of elements the stack can hold
//array            - your array
//newValue         - the value to be added to the stack
//insertionElement - the element index the newValue is to be stored at

if (elementCount < capacity) {
  for (int i = elementCount; i > insertionElement; --i) {
    array[i] = array[i-1];
  }
  array[insertionElement] = newValue;
  ++elementCount;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.