SimpleLinkedList add
Starting with the SimpleLinkedList
class provided below, complete the code for add
.
You'll want review the rest of the code to understand how this list implementation works and how to
walk a linked list and manipulate the references properly.
add
takes the position to add at as an int
as its first parameter and the Object
reference to add as its second.
add
should add the element to the list, increasing the size by one and shifting
elements after the add position backward.
You should assert
that the passed position is valid for this list.
But note that you should allow adding a new item to the end of the existing list.
When you are done, here is how your SimpleLinkedList
class should work:
public class SimpleLinkedList {
private class Item {
private Object value;
private Item next;
Item(Object setValue, Item setNext) {
value = setValue;
next = setNext;
}
}
private Item start;
private int size;
public SimpleLinkedList(Object[] values) {
assert values != null;
for (int i = values.length - 1; i >= 0; i--) {
add(0, values[i]);
}
size = values.length;
}
public int size() {
return size;
}
private Item walkTo(int index) {
assert index >= 0 && index < size;
int currentIndex = 0;
for (Item current = start; current != null; current = current.next) {
if (currentIndex == index) {
return current;
}
currentIndex++;
}
assert false;
return null;
}
public Object get(int index) {
return walkTo(index).value;
}
public void set(int index, Object newValue) {
walkTo(index).value = newValue;
}
public void add(int index, Object value) {
assert index == 0 : "General add not implemented yet";
start = new Item(value, start);
}
}