/* * File: stack2.cpp * Author: Leonid Reyzin (with thanks to David Metcalf) * Date: January 2003 * Class: CS112B1 * Assignment: Implementation of stack module using linked lists * -------------------------------------------------------------------- */ #include "stack2.h" /* declarations of public functions */ /*------------------------------------------------------------*/ /* StackNode::StackNode() constructor * Initializes a StackNode to point to NULL */ StackNode::StackNode() { next = NULL; } /*------------------------------------------------------------*/ /* StackNode::StackNode(newitem, newnext) constructor * Initializes a StackNode to contain newitem and point * to newnext */ StackNode::StackNode(ItemType newitem, StackNode * newnext) { item = newitem; next = newnext; } /*------------------------------------------------------------*/ /* Stack::Stack constructor * creates stack and initializes it to empty */ Stack::Stack() { list = NULL; } /*------------------------------------------------------------*/ /* Stack::Stack constructor * destroys the stack, freeing up memory */ Stack::~Stack() { Init(); } /*------------------------------------------------------------*/ /* Stack::Init: * Usage: stack.Init(); * Empties and re-initializes a stack. */ bool Stack::Init() { StackNode * newlist; while (list != NULL) { newlist = list->next; delete list; list = newlist; } list=NULL; return true; } /*------------------------------------------------------------*/ /* Stack::IsEmpty: * Usage: if(stack.IsEmpty()) {...} * checks whether a stack is empty. */ bool Stack::IsEmpty() { return (list==NULL); } /*------------------------------------------------------------*/ /* Stack::IsFull: * Usage: if(stack.IsFull()) {...} * checks whether a stack is full. * It never happens in this implementation. */ bool Stack::IsFull() { return false; } /*------------------------------------------------------------*/ /* Stack::Push: * Usage: flag= stack.Push(item); * pushes item onto stack. * returns true if successful, false if out of memory */ bool Stack::Push(ItemType item) { StackNode * newnode; newnode= new StackNode (item, list); if (newnode == NULL) return false; list = newnode; return true; } /*------------------------------------------------------------*/ /* Stack::Pop: * Usage: flag= stack.Pop(item); * Pops top item off stack; returns true unless * the stack is empty and there is nothing to pop * (i.e., returns false in case of stack underflow). */ bool Stack::Pop(ItemType &item) { // CODE GOES HERE StackNode * oldnode; if (IsEmpty()) return false; item = list -> item; oldnode = list; list = list -> next; delete oldnode; return true; } /* ----------- END OF FILE: stack.cpp ---------- */