I am trying to implement my custom LinkedList, with similar logic. Instead of generics and the Node class, I use my Element class. I only got one problem with one method. Perhaps I forgot or did not get enough sleep, but I cannot remember how to correctly display the values.
Here is some of the code from this class.
public class MyLinkedList implements MyList {
private int size = 0;
private Entity first;
private Entity last;
public MyLinkedList() {
}
static class Entity {
int value;
Entity next;
Entity prev;
public Entity(Entity prev, int value, Entity next) {
this.value = value;
this.next = next;
this.prev = prev;
}
}
interface MyList {
void add(int value);
MyList subList(int fromIndex, int toIndex);
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.add(13);
list.add(47);
list.add(65);
list.add(6);
System.out.println(list.subList(0, 2));
}
@Override
public void add(int value) {
Entity last = this.last;
Entity newData = new Entity(last, value, null);
this.last = newData;
if (last == null)
first = newData;
else
last.next = newData;
size++;
}
@Override
public MyList subList(int fromIndex, int toIndex) {
MyLinkedList result = new MyLinkedList();
for (int i = fromIndex; i < toIndex; i++) {
Entity entity = getEntity(i);
result.add(entity.value);
}
return result;
}
private Entity getEntity(int index) {
if (index > size) return null;
else {
Entity element = first;
for (int i = 0; i < index; i++)
element = element.next;
return element;
}
}
@Override
public String toString() {
return "MyLinkedList{" +
", first=" + first +
", last=" + last +
'}';
}
}
That is what console outputs:
MyLinkedList{, first=linkedlist.MyLinkedList$Entity@378bf509, last=linkedlist.MyLinkedList$Entity@5fd0d5ae}
What needs to be done to display the resultlike this?
[13, 47, 65]