Java Reference
In-Depth Information
Display 15.17
A Linked List with an Iterator
(part 3 of 3)
61
else
if
(position ==
null
|| previous ==
null
)
62
// list is empty or position is head node
63
LinkedList2.this.addtoStart(newData);
64
else
65
{
// previous and position are consecutive nodes
66
Node temp = new Node(newData, position)
67
previous.link = temp;
68
previous = temp;
69
}
70
}
71
/**
72
Changes the String in the node at location position.
73
Throws an IllegalStateException if position is not at a node,
74
*/
75
public
void changeHere(String newData)
<
The rest of the method
changeHere
is Self-Test Exercise 13.
>
76
/**
77
Deletes the node at location position and
78
moves position to the "next" node.
79
Throws an IllegalStateException if the list is empty.
80
*/
81
public
void
delete( )
82
{
83
if
(position ==
null
)
84
throw new
IllegalStateException( );
85
else
if
(previous ==
null
)
86
{
// remove node at head
87
head = head.link;
88
position = head;
89
}
90
else
// previous and position are consecutive nodes
91
{
92
previous.link = position.link;
93
position = position.link;
94
}
95
}
If
list
is an object of the
class
LinkedList2
, then
list.iterator( )
returns an iterator for list.
96
private
Node head;
97
public
List2Iterator iterator( )
98 {
99
return
new
List2Iterator( );
100 }
<
The other methods and constructors are identical to those in Displays 15.7 and 15.11.
>
101
}