// Chap 6, pp 264 - 266
// Rename this file as StackP.cpp
// *********************************************************
// Implementation file StackP.cpp for the ADT stack.
// Pointer-Based Implementation.
// *********************************************************
#include "StackP.h" // header file
#include // for NULL
#include // for asssert
struct stackNode
{ stackItemType Item;
ptrType Next;
}; // end struct
stackClass::stackClass() : TopPtr(NULL)
{
} // end default constructor
stackClass::stackClass(const stackClass& S)
{
if (S.TopPtr == NULL)
TopPtr = NULL; // original list is empty
else
{ // copy first node
TopPtr = new stackNode;
assert(TopPtr != NULL);
TopPtr->Item = S.TopPtr->Item;
// copy rest of list
ptrType NewPrev = TopPtr; // new list pointer
for (ptrType OrigCur = S.TopPtr->Next;
OrigCur != NULL;
OrigCur = OrigCur->Next)
{ NewPrev->Next = new stackNode;
assert(NewPrev->Next != NULL);
NewPrev = NewPrev->Next;
NewPrev->Item = OrigCur->Item;
} // end for
NewPrev->Next = NULL;
} // end if
} // end copy constructor
stackClass::~stackClass()
{
boolean Success;
// pop until stack is empty (Success is FALSE)
Pop(Success);
while (Success)
Pop(Success);
// Assertion: TopPtr == NULL
} // end destructor
boolean stackClass::StackIsEmpty()
{
return boolean(TopPtr == NULL);
} // end StackIsEmpty
void stackClass::Push(stackItemType NewItem,
boolean& Success)
{
// create a new node
ptrType NewTopPtr = new stackNode;
Success = boolean(NewTopPtr != NULL);
if (Success)
{ // allocation successful
// set data portion of new node
NewTopPtr->Item = NewItem;
// insert the new node
NewTopPtr->Next = TopPtr;
TopPtr = NewTopPtr;
} // end if
} // end Push
void stackClass::Pop(boolean& Success)
{
Success = boolean(!StackIsEmpty());
if (Success)
{ // stack is not empty; delete top
ptrType Temp = TopPtr;
TopPtr = TopPtr->Next;
// return deleted node to system
Temp->Next = NULL; // safeguard
delete Temp;
} // end if
} // end stackClass::Pop
void stackClass::GetStackTop(stackItemType& StackTop,
boolean& Success)
{
Success = boolean(!StackIsEmpty());
if (Success) // if stack is not empty,
StackTop = TopPtr->Item; // retrieve top
} // end GetStackTop
// End of implementation file.
               (
geocities.com/siliconvalley/program/2864/ds)                   (
geocities.com/siliconvalley/program/2864)                   (
geocities.com/siliconvalley/program)                   (
geocities.com/siliconvalley)