Java Reference
In-Depth Information
calls the constructor at lines 20-24 to set instance variable data to refer to the
insertItem passed as an argument and to set reference nextNode to null .
3. If the list is not empty, line 74 links the new node into the list by assigning to
lastNode and lastNode.nextNode the reference to the new ListNode that was
initialized with insertItem . ListNode 's constructor (lines 13-16) sets instance
variable data to refer to the insertItem passed as an argument and sets reference
nextNode to null , because this is the last node in the list.
In Fig. 21.7, part (a) shows a list and a new node during the insertAtBack operation
and before linking the new node into the list. The dotted arrows in part (b) illustrate Step
3 of method insertAtBack , which adds the new node to the end of a list that's not empty.
(a) firstNode
lastNode
new Listnode
12
7
11
5
(b) firstNode
lastNode
new Listnode
12
7
11
5
Fig. 21.7 | Graphical representation of operation insertAtBack .
21.4.7 List Method removeFromFront
Method removeFromFront (lines 78-92 of Fig. 21.3) removes the first node of the list and
returns a reference to the removed data. If the list is empty when the program calls this
method, the method throws an EmptyListException (lines 80-81). Otherwise, the meth-
od returns a reference to the removed data. The steps are:
1. Assign firstNode.data (the data being removed) to removedItem (line 83).
2. If firstNode and lastNode refer to the same object (line 86), the list has only one
element at this time. So, the method sets firstNode and lastNode to null (line
87) to remove the node from the list (leaving the list empty).
3. If the list has more than one node, then the method leaves reference lastNode as
is and assigns the value of firstNode.nextNode to firstNode (line 89). Thus,
firstNode references the node that was previously the second node in the list.
4. Return the removedItem reference (line 91).
In Fig. 21.8, part (a) illustrates the list before the removal operation. The dashed lines
and arrows in part (b) show the reference manipulations.
 
 
Search WWH ::




Custom Search