Java Reference
In-Depth Information
71
if
(isEmpty())
// firstNode and lastNode refer to same object
72
firstNode = lastNode =
new
ListNode<T>(insertItem);
73
else
// lastNode's nextNode refers to new node
74
lastNode = lastNode.nextNode =
new
ListNode<T>(insertItem);
75
}
76
77
// remove first node from List
78
public
T removeFromFront()
throws
EmptyListException
79
{
80
if
(isEmpty())
// throw exception if List is empty
81
throw new
EmptyListException(name);
82
83
T removedItem = firstNode.data;
// retrieve data being removed
84
85
// update references firstNode and lastNode
86
if
(firstNode == lastNode)
87
firstNode = lastNode =
null
;
88
else
89
firstNode = firstNode.nextNode;
90
91
return
removedItem;
// return removed node data
92
}
93
94
// remove last node from List
95
public
T removeFromBack()
throws
EmptyListException
96
{
97
if
(isEmpty())
// throw exception if List is empty
98
throw new
EmptyListException(name);
99
100
T removedItem = lastNode.data;
// retrieve data being removed
101
102
// update references firstNode and lastNode
103
if
(firstNode == lastNode)
104
firstNode = lastNode =
null
;
105
else
// locate new last node
106
{
107
ListNode<T> current = firstNode;
108
109
// loop while current node does not refer to lastNode
110
while
(current.nextNode != lastNode)
111
current = current.nextNode;
112
113
lastNode = current;
// current is new lastNode
114
current.nextNode =
null
;
115
}
116
117
return
removedItem;
// return removed node data
118
}
119
Fig. 21.3
|
ListNode
and
List
class declarations. (Part 3 of 4.)