1: // Created by Frank M. Carrano and Timothy M. Henry. 2: // Copyright (c) 2017 Pearson Education, Hoboken, New Jersey. 4: template<class ItemType> 5: LinkedBag<ItemType>::LinkedBag(const LinkedBag<ItemType>& aBag) 6: { 7: itemCount = aBag.itemCount; 8: Node<ItemType>* origChainPtr = aBag.headPtr; // Points to nodes in original chain 9: 10: if (origChainPtr == nullptr) 11: headPtr = nullptr; // Original bag is empty 12: else 13: { 14: // Copy first node 15: headPtr = new Node<ItemType>(); 16: headPtr->setItem(origChainPtr->getItem()); 17: 18: // Copy remaining nodes 19: Node<ItemType>* newChainPtr = headPtr; // Points to last node in new chain 20: origChainPtr = origChainPtr->getNext(); // Advance original-chain pointer 21: 22: while (origChainPtr != nullptr) 23: { 24: // Get next item from original chain 25: ItemType nextItem = origChainPtr->getItem(); 26: 27: // Create a new node containing the next item 28: Node<ItemType>* newNodePtr = new Node<ItemType>(nextItem); 29: 30: // Link new node to end of new chain 31: newChainPtr->setNext(newNodePtr); 32: 33: // Advance pointer to new last node 34: newChainPtr = newChainPtr->getNext(); 35: 36: // Advance original-chain pointer 37: origChainPtr = origChainPtr->getNext(); 38: } // end while 39: 40: newChainPtr->setNext(nullptr); // Flag end of new chain 41: } // end if 42: } // end copy constructor