Java Reference
In-Depth Information
Back , removeFromFront and removeFromBack . Method insertAtFront (lines 60-66 of
Fig. 21.3) places a new node at the front of the list. The steps are:
1. Call isEmpty to determine whether the list is empty (line 62).
2. If the list is empty, assign to firstNode and lastNode the new ListNode that was
initialized with insertItem (line 63). (Recall that assignment operators evaluate
right to left.) The ListNode constructor at lines 13-16 calls the ListNode con-
structor 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 , because this is the
first and last node in the list.
3. If the list is not empty, the new node is “linked” into the list by setting firstNode
to a new ListNode object and initializing that object with insertItem and
firstNode (line 65). When the ListNode constructor (lines 20-24) executes, it
sets instance variable data to refer to the insertItem passed as an argument and
performs the insertion by setting the nextNode reference of the new node to the
ListNode passed as an argument, which previously was the first node.
In Fig. 21.6, part (a) shows a list and a new node during the insertAtFront operation
and before the program links the new node into the list. The dotted arrows in part (b) illus-
trate Step 3 of the insertAtFront operation that enables the node containing 12 to
become the new first node in the list.
(a)
firstNode
7
11
new ListNode
12
(b)
firstNode
7
11
new ListNode
12
Fig. 21.6 | Graphical representation of operation insertAtFront .
21.4.6 List Method insertAtBack
Method insertAtBack (lines 69-75 of Fig. 21.3) places a new node at the back of the list.
The steps are:
1. Call isEmpty to determine whether the list is empty (line 71).
2. If the list is empty, assign to firstNode and lastNode the new ListNode that was
initialized with insertItem (line 72). The ListNode constructor at lines 13-16
 
 
Search WWH ::




Custom Search