-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedIntList.java
More file actions
103 lines (91 loc) · 2.29 KB
/
LinkedIntList.java
File metadata and controls
103 lines (91 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Implement a linked list of integers
public class LinkedIntList {
// first value in the list
private ListNode front;
// construct an empty list
public LinkedIntList() {
front = null;
}
// return number of elements in the list
public int size() {
int count = 0;
ListNode current = front;
while (current != null) {
current = current.next;
count++;
}
return count;
}
// return the integer at the given index. assumes 0 <= index < size()
public int get(int index) {
return nodeAt(index).data;
}
// return the position of the first occurrence of the value
// return -1 if not found
public int indexOf(int value) {
int index = 0;
ListNode current = front;
while (current != null) {
if (current.data == value) {
return index;
}
index++;
current = current.next;
}
return -1;
}
// append given value to the end of the list
public void add(int value) {
if (front == null) {
front = new ListNode(value);
} else {
ListNode current = front;
while (current.next != null) {
current = current.next;
}
current.next = new ListNode(value);
}
}
// inserts given value at the given index. assumes 0 <= index <= size()
public void add(int index, int value) {
if (index == 0) {
front = new ListNode(value, front);
} else {
ListNode current = nodeAt(index - 1);
current.next = new ListNode(value, current.next);
}
}
// remove value at the given index. assumes pre : 0 <= index < size()
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
ListNode current = nodeAt(index - 1);
current.next = current.next.next;
}
}
// helper method: return a reference to the node at the given index
// assumes0 <= i < size()
private ListNode nodeAt(int index) {
ListNode current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current;
}
// create a printable version of the list
public String toString() {
if (front == null) {
return "[]";
} else {
String result = "[" + front.data;
ListNode current = front.next;
while (current != null) {
result += ", " + current.data;
current = current.next;
}
result += "]";
return result;
}
}
}