This page is very incomplete. I strongly recommend that you read the appropriate sections of Sedgewick's Algorithms book.
int s[10]; /* stack can hold a max of 10 ints */
int num = 0; /* number of items on stack, initially 0 */
void push(int item)
{
s[num] = item; /* add new item to stack */
num++; /* adjust item count */
}
int pop()
{
num--; /* adjust item count */
return s[num]; /* return item on top of stack */
}
Notice that since elements in an array are indexed from 0 to
n-1, the first item on the stack will be put into s[0],
the second into s[1], and so on. If there are k items on
the stack, then they are stored in s[0] -> s[k -
1], so the next item we push onto the stack should be placed
in s[k].
So, if the top item of a stack is stored at s[num - 1], we
need to subtract 1 from num before we return the element. Notice
also that it was important to update num before we returned the
element, since the return statement will be the last one executed
in the function.
With an array-based implementation of a stack, you need to be
careful not to push an element onto a full stack. Also, keep in
mind that popping an item from the stack doesn't actually remove
it from the array. You can't 'remove' an item from an array. You
can only over-write one element with another. So, if you execute a
'pop' and then a 'push', the new item will be written to the array
in place of the old one.
T U T
R S S S O O O O O
I I I T T T T T T T T T T
I N F F F F F F F F F F F F F F F
T T T T T T T T T T T T T T T T T T T T T
A S S S S S S S S S S S S S S S S S S S S S S S
L L L L L L L L L L L L L L L L L L L L L L L L L L L
-----------------------------------------------------
L A * S T I * N * F I R * S T * * O U * T * * * * * *
s[0] always holds the bottom of the stack, if there's anything on it (or s[0] holds whatever was last
at the bottom of the stack, if there's nothing on it.) So s[0] is L. Then, even though everything
else has been 'popped', S, T, F, and T were the last items in s[1]-s[4]. So the answer should be
LSTFT. (The solution is off-by-1.)