Well, the easy thing to do is maintain the index of the top of the array. Popping an item from your stack is a simple matter of decrementing that number. You don't actually delete anything from the stack, you just say that a different index is the top.
For example, let's look at your example. We start with an empty stack:
Value:
Index: 0 1 2 3 4 5 6 7 8 9
Top: -1
We assume that a negative "Top" means the array is empty. A "Top" of 0 indicates that one item is in the array -- that the "top" of the stack is at index 0 of the array.
Let's push your '2' onto the stack.
Value: 2
Index: 0 1 2 3 4 5 6 7 8 9
Top: 0
Now let's push 3.
Value: 2 3
Index: 0 1 2 3 4 5 6 7 8 9
Top: 1
See how the "Top" refers to the index in the array that represents the top of the stack? Let's insert the rest of your numbers:
Value: 2 3 5 7 4 9
Index: 0 1 2 3 4 5 6 7 8 9
Top: 5
Now we have 6 items in the array. The top of the stack is at index 5. Notice also that the number of items in the array is always (Top + 1). (An empty array has a top of -1, so (-1 + 1) = 0.)
Now we want to remove an item from the array. This is a simple matter of making sure the array isn't already empty, and just decrementing Top:
Value: 2 3 5 7 4 9
Index: 0 1 2 3 4 5 6 7 8 9
Top: 4
Notice that "9" is still in the array, but Top is 4, which identifies the value of "4" as the top of the stack. If we insert a new number, say 1, into the array, it will overwrite the 9:
Value: 2 3 5 7 4 1
Index: 0 1 2 3 4 5 6 7 8 9
Top: 5
Here's a simple class that illustrates this concept. I do not guarantee correctness -- I'm just typing into the text area. It's your responsibility to understand and debug the code:
#define INTSTACK_SIZE 10
class IntStack
{
public:
IntStack() { /* empty */ }
~IntStack() { /* empty */ }
int size()
{
return top_ + 1;
}
bool push(int x)
{
bool ret = false;
// only insert item if there's room:
if (size() < INTSTACK_SIZE)
{
arr_[++top_] = x;
ret = true;
}
return ret;
}
bool pop(int * top)
{
bool ret = false;
// Only can pop from a nonempty stack:
if (size() > 0)
{
*top = arr_[top_--];
ret = true;
}
}
bool top(int * top)
{
bool ret = false;
// Only can get top from a nonempty stack:
if (size() > 0)
{
*top = arr_[top_];
ret = true;
}
}
private:
int[INTSTACK_SIZE] arr_;
int top_;
};
The accessor functions push(), pop(), and top() return true if they succeed. pop() and top() return the actual top value via the int pointer passed into the function.
Another way of writing this class is to return the int values as expected and throw exceptions if something goes wrong. Exceptions include Stack Overflow (pushing onto a full stack) and Stack Underflow (popping or topping an empty stack).
Hope this helps!
Take care,
Nik
http://www.bigaction.org/