1: // Created by Frank M. Carrano and Timothy M. Henry.
2: // Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.
4: // Listing C4-3
6: template<class ItemType>
7: bool LinkedList<ItemType>::insert(int newPosition,
8: const ItemType& newEntry)
9: {
10: bool ableToInsert = (newPosition >= 1) &&
11: (newPosition <= itemCount + 1);
12: if (ableToInsert)
13: {
14: // Create a new node containing the new entry
15: auto newNodePtr = std::make_shared<Node<ItemType>>(newEntry);
16:
17: // Attach new node to chain
18: if (newPosition == 1)
19: {
20: // Insert new node at beginning of chain
21: newNodePtr–>setNext(headPtr);
22: headPtr = newNodePtr;
23: }
24: else
25: {
26: // Find node that will be before new node
27: auto prevPtr = getNodeAt(newPosition – 1);
28:
29: // Insert new node after node to which prevPtr points
30: newNodePtr–>setNext(prevPtr –>getNext());
31: prevPtr–>setNext(newNodePtr);
32: } // end if
33:
34: itemCount++; // Increase count of entries
35: } // end if
36:
37: return ableToInsert;
38: } // end insert