Stacks

637 Words2 Pages

Stacks

Data Structures and Algorithms

3.3 Stacks

Another way of storing data is in a stack. A stack is generally implemented with only two principle operations (apart from a constructor and destructor methods):

push adds an item to a stack

pop extracts the most recently pushed item from the stack

Other methods such as

top returns the item at the top without removing it [9]

isempty determines whether the stack has anything in it

are sometimes added.

A common model of a stack is a plate or coin stacker. Plates are "pushed" onto to the top and "popped" off the top. Stacks form Last-In-First-Out (LIFO) queues and have many applications from the parsing of algebraic expressions to ...

A formal specification of a stack class would look like:

typedef struct t_stack *stack;

stack ConsStack( int max_items, int item_size );

/* Construct a new stack

Pre-condition: (max_items * 0) && (item_size * 0)

Post-condition: returns a pointer to an empty stack

*/

void Push( stack s, void *item );

/* Push an item onto a stack

Pre-condition: (s is a stack created by a call to ConsStack) &&

(existing item count * max_items) &&

(item != NULL)

Post-condition: item has been added to the top of s

*/

void *Pop( stack s );

/* Pop an item of a stack

Pre-condition: (s is a stack created by a call to

ConsStack) &&

(existing item count *= 1)

Post-condition: top item has been removed from s

*/

Points to note:

a. A stack is simply another collection of data items and thus it would be possible to use exactly the same specification as the one used for our general collection. However, collections with the LIFO semantics of stacks are so important in computer science that it is appropriate to set up a limited specification appropriate to stacks only.

b. Although a linked list implementation of a stack is possible (adding and deleting from the head of a linked list produces exactly the LIFO semantics of a stack), the

Open Document