Code Implementation
// DYNAMICALLY LINKED IMPLEMENTATION OF STACK
Struct NodeType; //Forward declaration
class StackType
{
public:
//Identical to previous implementation
private:
NodeType* topPtr;
};
.
.
.
Struct NodeType
{
ItemType info;
NodeType* next;
};
void StackType::Push ( ItemType newItem )
// Adds newItem to the top of the stack.
{
if (IsFull())
throw FullStack();
NodeType* location;
location = new NodeType;
location->info = newItem;
location->next = topPtr;
topPtr = location;
void StackType::Pop() // Remove top item from Stack.
{
if (IsEmpty())
throw EmptyStack();
else
{
NodeType* tempPtr;
tempPtr = topPtr;
topPtr = topPtr ->next;
delete tempPtr;
}
}
ItemType StackType::Top()
// Returns a copy of the top item in the stack.
{
if (IsEmpty())
throw EmptyStack();
else
return topPtr->info;
}
bool StackType::IsFull() const
// Returns true if there is no room for another
// ItemType on the free store; false otherwise
{
NodeType* location;
try
{
location = new NodeType;
delete location;
return false;
}
catch(std::bad_alloc exception)
{
return true;
}
}
When a local stack variable goes out of
scope, the memory space for data member topPtr is deallocated. But
the nodes that topPtr points to are not automatically deallocated.........NEED
a DESTRUCTOR
stackType::~StackType()
// Post: stack is empty;
// All items have been deallocated.
{
NodeType* tempPtr;
while (topPtr != NULL)
{
tempPtr = topPtr;
topPtr = topPtr-> next;
delete tempPtr;
}
}
|