Stacks

A classic data structure giving Last-In, First-Out (LIFO) or Last-Come, First-Serve (LCFS) access to elements.

Examples: stack of cards, stack of checkers.

Basic operations: push, pop, also initialize, full, empty.

Used for evaluating expression with Reverse Polish Notations:
2 * 3 - 4 as 2 3 * 4 -

1 + 2 * 4 as 1 2 4 * +

Stack Implementation

A stack is an example of an abstract data type.

Includes data plus operations that can be performed on the data. Only the use of these operations can be used to change the data.

Could implement ADT with separate functions and data or could just integrate data and operations as an object--approach we will take.

Look at example of reversing a line of text. Note the basic operations and the inclusion of the stack as an argument.

/* /cs/cs2005/pub/example/stack.h -- header file for stack example */

#define MAXSTACK 10

typedef char Item_type;

typedef short Boolean;

class Stack {
  private:
    int top;        /* top of stack */
    Item_type rgItem[MAXSTACK];
  public:
    Stack();
    Boolean EmptyStack();
    Boolean FullStack();
    int Push(Item_type item);
    int Pop(Item_type &item);
};

/*
 * /cs/cs2005/pub/example/stack.C -- stack routines
 */

#include "stack.h"

/*
 * Stack - initialize the stack
 */
Stack::Stack()
{
    top = 0;
}

/*
 * Push - push an item on the stack, return zero for success, -1 on error.
 */
int Stack::Push(Item_type item)
{
    if (top >= MAXSTACK)
        return(-1);
    else {
        rgItem[top++] = item;
        return(0);
    }
}

/*
 * Pop - pop an item off the stack, return zero for success, -1 on error.
 */
Stack::Pop(Item_type &item)
{
    if (top <= 0)
        return(-1);
    else {
        item = rgItem[--top];
        return(0);
    }
}

/*
 * FullStack - is the stack full?
 */
Boolean Stack::FullStack()
{
    return(top >= MAXSTACK);
}

/*
 * EmptyStack - is the stack empty?
 */
Boolean Stack::EmptyStack()
{
    return(top <= 0);
}

/*
 * /cs/cs2005/pub/example/reverseread.C -- reverse a line
 *
 * compile: g++ -o reverseread reverseread.C stack.C
 *
 * alternate: g++ -c reverseread.C
 *            g++ -c stack.C
 *            g++ -o reverseread reverseread.o stack.o
 */

#include <iostream.h>
#include "stack.h"

void main(void)
{
    Stack stack;
    Item_type item;

    // read a character and check for end-of-file (^D) on input
    // cin of a character does not read newline char
    while ((cin >> item) && (!cin.eof())) {
        if (stack.Push(item) < 0) {
            cout << "No more room on stack.\n";
            exit(1);
        }
    }

    while (stack.Pop(item) >= 0)
        cout << item;
    cout << "\n";
}