Member Functions for Stack ADT - Pointer-based Implementation
// ********************************************************* // Implementation file StackP.cpp for the ADT stack. // Pointer-based implementation. // ********************************************************* #include "Stackptr.h" // header file #include// for NULL #include // for assert struct stackNode { stackItemType Item; ptrType Next; }; // end struct Stack::Stack() : TopPtr(NULL) { } // end default constructor Stack::Stack(const Stack& 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 NewPtr = TopPtr; // new list pointer for (ptrType OrigPtr = S.TopPtr->Next; OrigPtr != NULL; OrigPtr = OrigPtr->Next) { NewPtr->Next = new stackNode; assert(NewPtr->Next != NULL); NewPtr = NewPtr->Next; NewPtr->Item = OrigPtr->Item; } // end for NewPtr->Next = NULL; } // end if } // end copy constructor Stack::~Stack() { int Success; // pop until stack is empty (Success is false) Success = pop(); while (Success) Success = pop(); // Assertion: TopPtr == NULL } // end destructor int Stack::isEmpty() { return (TopPtr == NULL); } // end StackIsEmpty int Stack::push(stackItemType NewItem) { // create a new node ptrType NewPtr = new stackNode; int Success = (NewPtr != NULL); // check allocation if (Success) { // allocation successful; set data portion of new node NewPtr->Item = NewItem; // insert the new node NewPtr->Next = TopPtr; TopPtr = NewPtr; } // end if return Success; } // end Push int Stack::pop() { int Success = (!isEmpty()); 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 return Success; } // end Pop int Stack::pop(stackItemType& StackTop) { int Success = (!isEmpty()); if (Success) { // stack is not empty; retrieve and delete top StackTop = TopPtr->Item; ptrType Temp = TopPtr; TopPtr = TopPtr->Next; // return deleted node to system Temp->Next = NULL; // safeguard delete Temp; } // end if return Success; } // end Pop int Stack::top(stackItemType& StackTop) { int Success = (!isEmpty()); if (Success) // stack is not empty; retrieve top StackTop = TopPtr->Item; return Success; } // end GetStackTop // End of implementation file.
Email Me | Office Hours | My Home Page | Department Home | MCC Home Page