Stacks

Introduction

The primary characteristic of a stack is that the last thing out is the first thing in. This is called LIFO. In real life, this is the way that cafeteria trays that are stacked on a spring work. The topmost one is the one that will be taken next. Its definition is independent of the way it is implemented as are all the data structures more complex than an array. There are four operations used on a stack; push pop is_stk_empty and is_stk_full . There is also a pointer to a location on the stack. This is the top of stack (TOS) pointer and it indicates the place where the next item will be added or removed. Only the item at the top of the stack can be referred to. Any reference to the underlying data structure is illegal By always using the routines described above, the LIFO characteristic of the stack is preserved. The routines below use arrays but it is vital that you not confuse stacks and arrays. Stacks can be implemented using arrays but that is not the only way.
int STK[MAXSTK];
int TOS=0;

int 
pop()
{
/* return the integer at the Top of stack */
   if(! is_stk_empty() {
      TOS -= 1;
      return(STK[TOS+1];
   }
} // pop

void
push(int item)
{
/* store item at top of stack */
   if (! is_stk_full() ) {
      TOS += 1;
      STK[TOS] = item;
   }
} // push

bool
is_stk_full()
{
/* returns true if stack is full */
   if(TOS == MAXSTK) {
     return(true);
   else
     return(false);
   }
} // is_stk_full

bool
is_stk_empty() 
{
 /* return true if stack is empty */
   if (TOS == 0) {
      return(true);
   else
      return(false);
   }
} // is_stk_empty
With this implementation, the TOS pointer always points at the object that is on the top of the stack. A drawback to this implementation is that the stack is of fixed size. It can never get larger than the array that contains it.

Uses For Stacks

The most common use is for maintaining parameters and return addresses for subroutine calls. They are also used for temporary storage of information and reversing things. Think of how an undo command works. It undoes in the opposite order that things were done. A stack is a natural for this.