The ADT designer writes the
stack ADT specification:
|
Prototype: Stack(); Purpose: Create an empty stack. Precondition: None. Postcondition:
An empty stack has been created. Prototype: void
Push( /* in */ ItemType newItem ); Purpose: Add
newItem to the top of the stack. Precondition: The
stack is not full. Postcondition:
The newItem has
been added to the top of the stack. Prototype: ItemType
Pop(); Purpose: Remove
and return the item from the top of the stack. Precondition: The
stack is not empty. Postcondition: The stack's topmost item has been
removed from the stack. Function value =
the item that was at the top of the stack. Prototype: ItemType Top()
const; Purpose: Returns
a copy of the item from the top of the stack. Precondition: The
stack is not empty. Postcondition:
Function value = a copy of the
item that is at the top of the stack. Prototype: bool
IsEmpty() const; Purpose: Test
whether the stack is empty. Precondition: None. Postcondition:
Function value = true, if the
stack is empty; false if the stack is not empty. Prototype: bool
IsFull() const; Purpose: Test
whether the stack is full. Precondition:
None. Postcondition: Function value = true, if the stack
is full; false if the stack is not full. |
The ADT implementer codes the
stack header and the stack implementation.
Header file:
stack.h
|
#ifndef STACK_H #define STACK_H const int MAX_SIZE =
100; typedef int Item; class Stack { public: Stack(); void Push( /* in */ Item newItem ); Item Top() const; Item Pop(); bool IsEmpty() const; bool IsFull() const; private: Item items[MAX_SIZE]; int
top; // index of top
item. -1 == stack is empty }; #endif |
Implementation file: stack.cpp
#include
"stack.h"
Stack::Stack( void )
{
top = -1;
}
void Stack::Push( /* in
*/ Item newItem )
{
top++;
items[top] = newItem;
}
Item Stack::Top() const
{
return items[top];
}
Item Stack::Pop()
{
Item item = items[top];
top--;
return item;
}
bool Stack::IsEmpty()
const
{
return ( top == -1 );
}
bool Stack::IsFull()
const
{
return ( top == MAX_SIZE-1 );
}