Java Reference
In-Depth Information
33 String result = "[" + front.data;
34 ListNode current = front.next;
35
while
(current != null) {
36 result += ", " + current.data;
37 current = current.next;
38 }
39 result += "]";
40
return
result;
41 }
42 }
43
44 // post: returns the position of the first occurrence of the
45 // given value (-1 if not found)
46
public int
indexOf(
int
value) {
47
int
index = 0;
48 ListNode current = front;
49
while
(current != null) {
50
if
(current.data == value) {
51
return
index;
52 }
53 index++;
54 current = current.next;
55 }
56
return
-1;
57 }
58
59 // post: appends the given value to the end of the list
60
public void
add(int value) {
61
if
(front == null) {
62 front =
new
ListNode(value);
63 }
else
{
64 ListNode current = front;
65
while
(current.next != null) {
66 current = current.next;
67 }
68 current.next =
new
ListNode(value);
69 }
70 }
71
72 // pre: 0 <= index <= size()
73 // post: inserts the given value at the given index
74
public void
add(
int
index,
int
value) {
75
if
(index == 0) {
76 front =
new
ListNode(value, front);
Search WWH ::
Custom Search