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) 
      myArray[myTop] = value;
      cerr << "*** Stack full -- can't add new value ***\n"
              "Must increase value of STACK_CAPACITY in Stack.h\n";

Edited by bmos31: didnt finish my post

6 Years
Discussion Span
Last Post by Fbody

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;

Edited by Fbody: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.