Java Reference
In-Depth Information
Display 15.17
A Linked List with an Iterator
(part 2 of 3)
22
public void
restart( )
23 {
24 position = head;
//Instance variable head of outer class.
25 previous =
null
;
26 }
27
public
String next( )
28 {
29
if
(!hasNext( ))
30
throw new
NoSuchElementException( );
31 String toReturn = position.item;
32 previous = position;
33 position = position.link;
34
return
toReturn;
35 }
36
public boolean
hasNext( )
37 {
38
return
(position !=
null
);
39 }
40
/**
41
Returns the next value to be returned by next( ).
42
Throws an IllegalStateExpression if hasNext( ) is false.
43
*/
44
public
String peek( )
45 {
46
if
(!hasNext( ))
47
throw new
IllegalStateException( );
48
return
position.item;
49 }
50
/**
51
Adds a node before the node at location position.
52
previous is placed at the new node. If hasNext( ) is
53
false, then the node is added to the end of the list.
54
If the list is empty, inserts node as the only node.
55
*/
56
public void
addHere(String newData)
57 {
58
if
(position ==
null
&& previous !=
null
)
59
// at end of the list, add to end
60 previous.link =
new
Node(newData,
null
);
61
else if
(position ==
null
|| previous ==
null
)
62
// list is empty or position is head node
63 LinkedList2.this.addtoStart(newData);
(continued)