Stacks


What is a Data Structure?

A data structure is a component or object that stores and provides access to information. Arrays and linked lists are examples of rudimentary data structures. Arrays store a fixed number of objects and can provide random access to any of those objects. Linked lists store a dynamic number of objects and provide access to only the first object in the list at any given time.

Other examples of data structures include stacks, queues, and trees. Each data structure differs with respect to how it provides access to information and how efficient its operations are. All data structures enable the programmer to insert and remove data. However, stacks only allow the programmer to remove the last piece of data inserted. Queues allow the programmer to remove the piece of data that has been in the queue the longest.

Overview of Stacks

A stack is a last-in first-out data structure (LIFO). Conceptually, the stack data structure behaves like a stack of books or a stack of plates. New data is placed on the top of the stack, and when data is removed it is taken from the top. Your browser's back button likely stores a set of URLs in a stack.

The operations supported by a stack are as follows:

Stacks are typically depicted as follows:

stack

The previous stack would be the result of the following operations:

push(1)

push(2)

push(3)

A pop on the stack above would return the object 3 and the resulting stack would look as follows:

stacks 2

A top on the stack above would return the object 2 and the stack itself would remain unchanged.

Implementation

A stack can be implemented using an array or a linked list. In essense, the stack operations simply limit the way in which we access data stored in a data structure such as an array. A stack can also be implemented using other data structures, but we'll discuss that example later.

When choosing which rudimentary data structure to use for an implementation, it is imperative that you consider efficiency. How many steps will push and pop require?

To implement a stack, you will need to implement a Stack class that provides the stack operations described above. You will also want to provide appropriate error reporting. Therefore, it might make sense to have the pop operation throw a StackEmptyException in the event that the programmer tries to pop from a stack with no elements.

+Implementing a Stack Using an Array

+Implementing a Stack Using a Linked List


Sami Rollins

Date: 2007-10-10