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