1: // Created by Frank M. Carrano and Tim Henry. 2: // Copyright (c) 2013 __Pearson Education__. All rights reserved. 4: /** Listing 7-4. 5: @file LinkedStack.cpp */ 7: #include <cassert> // For assert 8: #include "LinkedStack.h" // Header file 10: template<class ItemType> 11: LinkedStack<ItemType>::LinkedStack() : topPtr(nullptr) 12: { 13: } // end default constructor 15: template<class ItemType> 16: LinkedStack<ItemType>::LinkedStack(const LinkedStack<ItemType>& aStack) 17: { 18: // Point to nodes in original chain 19: Node<ItemType>* origChainPtr = aStack->topPtr; 20: 21: if (origChainPtr == nullptr) 22: topPtr = nullptr; // Original bag is empty 23: else 24: { 25: // Copy first node 26: topPtr = new Node<ItemType>(); 27: topPtr->setItem(origChainPtr->getItem()); 28: 29: // Point to last node in new chain 30: Node<ItemType>* newChainPtr = topPtr; 31: 32: // Copy remaining nodes 33: while (origChainPtr != nullptr) 34: { 35: // Advance original-chain pointer 36: origChainPtr = origChainPtr->getNext(); 37: 38: // Get next item from original chain 39: ItemType nextItem = origChainPtr->getItem(); 40: 41: // Create a new node containing the next item 42: Node<ItemType>* newNodePtr = new Node<ItemType>(nextItem); 43: 44: // Link new node to end of new chain 45: newChainPtr->setNext(newNodePtr); 46: 47: // Advance pointer to new last node 48: newChainPtr = newChainPtr->getNext(); 49: } // end while 50: 51: newChainPtr->setNext(nullptr); // Flag end of chain 52: } // end if 53: } // end copy constructor 55: template<class ItemType> 56: LinkedStack<ItemType>::~LinkedStack() 57: { 58: // Pop until stack is empty 59: while (!isEmpty()) 60: pop(); 61: } // end destructor 63: template<class ItemType> 64: bool LinkedStack<ItemType>::isEmpty() const 65: { 66: return topPtr == nullptr; 67: } // end isEmpty 69: template<class ItemType> 70: bool LinkedStack<ItemType>::push(const ItemType& newItem) 71: { 72: Node<ItemType>* newNodePtr = new Node<ItemType>(newItem, topPtr); 73: topPtr = newNodePtr; 74: newNodePtr = nullptr; 75: 76: return true; 77: } // end push 79: template<class ItemType> 80: bool LinkedStack<ItemType>::pop() 81: { 82: bool result = false; 83: if (!isEmpty()) 84: { 85: // Stack is not empty; delete top 86: Node<ItemType>* nodeToDeletePtr = topPtr; 87: topPtr = topPtr->getNext(); 88: 89: // Return deleted node to system 90: nodeToDeletePtr->setNext(nullptr); 91: delete nodeToDeletePtr; 92: nodeToDeletePtr = nullptr; 93: 94: result = true; 95: } // end if 96: 97: return result; 98: } // end pop 100: template<class ItemType> 101: ItemType LinkedStack<ItemType>::peek() const 102: { 103: assert(!isEmpty()); // Enforce precondition 104: 105: // Stack is not empty; return top 106: return topPtr->getItem(); 107: } // end getTop 108: // End of implementation file.