Redefining implentation of a push function for an array-based Stack class

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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
   }
}
one way would be
1
2
3
4
5
6
7
8
9
10
11
void Stack::push(const StackElement & value)
{
   //'size' is the number of elements stored in stack
   if (size< STACK_CAPACITY) 
   { 
      for(int i = size-1; i >=0; i--)//shift the whole array
         myArray[i+1] = myArray[i];

      myArray[0] = value;
   }
}
another one would be to change operator[] ..
Oh, wow, thanks. I was trying to include myTop in the function, but this makes it unecessary. Much appreciated!
Topic archived. No new replies allowed.