AI Horizon: Intelligence and Reason in Computers
Introduction Home Essays Resources Contact Info
Essays
  Basic CS
General AI
Chess AI
Go AI

Resources
  Source Code
AI Tips and Tricks
Books
Links

Other
  Code Journal
Site Updates

An Affiliate of Cprogramming.com
 

Stacks
(Up to Basic Computer Science : Lists and Arrays)

Stacks are a type of list in which all inserts and removals happen at one end. Imagine a normal stack of cafeteria trays: to get one, you take it off the top, and to put one on, you pile it on the top. The first tray to be put into the stack is the last one taken off. This can be generalized to this short acronym: Last In, First Out (LIFO).

This is a simple concept, and a stack is really easy to make. Before we make a stack, however, you should learn some standard jargon.

To add an object to the top of a stack is called to push that object onto the stack, and to take an object off the top of the stack is to pop it off the stack. To glance a couple layers down from the top is to peek.

Easy, right? Now, on to the actual code:

( About Example C++ code )
class stack
{
  public:
    stack(void);                // Constructor and Initializer

    bool push(int data);        // Push onto stack
    bool pop(int data);         // Pop from stack
    int  peek(int depth);       // Peek several layers down

  private:
    const int MAX_SIZE;         // Maximum stack size
    int   stack_data[MAX_SIZE]; // Stack Data Array
    int   stack_top;            // Keeps track of Stack Top
};

This should be pretty straightforward to read. I've used a constant size to keep the code relatively simple. This is called a static-implementation of the stack, meaning that the size won't change after it is initialized. but if you know how to use pointers, you can use dynamic allocation and make the stack size-adjustable. For instance, this is how the apstack class is often implemented. If you do not understand pointers, please consult a book on C or C++ or an internet site such as Cprogramming.com.

Download from Source Code Repository: lists/stack.h

All content is written and published by the people at or affiliated with AI Horizon <http://www.aihorizon.com/>.
Send any comments and suggestions to [email protected].

Please report any errors to [email protected].