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 assign it firstNode (line 107).

4. Now “walk the list” with current until it references ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.