Java Reference
In-Depth Information
(a) firstNode
lastNode
12
7
11
5
(b) firstNode
lastNode
12
7
11
5
removeItem
Fig. 21.8 | Graphical representation of operation removeFromFront .
21.4.8 List Method removeFromBack
Method removeFromBack (lines 95-118 of Fig. 21.3) removes the last node of a list and
returns a reference to the removed data. The method throws an EmptyListException
(lines 97-98) if the list is empty when the program calls this method. The steps are:
1. Assign lastNode.data (the data being removed) to removedItem (line 100).
2. If the firstNode and lastNode refer to the same object (line 103), the list has
only one element at this time. So, line 104 sets firstNode and lastNode to null
to remove that node from the list (leaving the list empty).
3. If the list has more than one node, create the ListNode reference current and as-
sign it firstNode (line 107).
4. Now “walk the list” with current until it references the node before the last node.
The while loop (lines 110-111) assigns current.nextNode to current as long as
current.nextNode (the next node in the list) is not lastNode .
5. After locating the second-to-last node, assign current to lastNode (line 113) to
update which node is last in the list.
6. Set the current.nextNode to null (line 114) to remove the last node from the
list and terminate the list at the current node.
7. Return the removedItem reference (line 117).
In Fig. 21.9, part (a) illustrates the list before the removal operation. The dashed lines
and arrows in part (b) show the reference manipulations. [We limited the List insertion
 
 
Search WWH ::




Custom Search