I am learning the basics of Java while taking a data structures course. I feel that I have the logic correctly laid out in my code, but I am unable to get the tests to pass. Hoping someone could take some time to loot at my Java implementation and let me know if I am missing any key details to get the methods below working.
This is the class as provided:
import java.util.Iterator;
public class LinkedList<T> implements Iterable<T> {
static class ListNode<T> {
ListNode<T> prev;
ListNode<T> next;
T value;
ListNode(T value) {
this.value = value;
}
}
protected ListNode<T> head;
protected ListNode<T> tail;
private int size = 0;
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
ListNode<T> current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T value = current.value;
current = current.next;
return value;
}
};
}
Of the methods I need to implement I am interested in learning why these two do not work and I think I can figure out the rest from there:
The first is to remove:
public boolean remove(T value) {
if(head == null){
return false;
} else if(head == value) {
removeFront();
return true;
} else {
ListNode<T> current = head;
ListNode<T> prev = null;
while(current != null) {
if(!current.equals(value)) {
prev = current;
current = current.next;
} else if(current == tail) {
removeEnd();
return true;
}
else {
ListNode<T> temp = current.next;
prev.next = temp;
temp.prev = current.prev;
current = null;
}
}
}
return false;
}
The second is contains()
public boolean contains(T value) {
boolean found = false;
if(head.value.equals(value)){
found=true;
return found;
}
ListNode<T> current = head.next;
while(current.value != null && !found) {
if (current.value.equals(value)) {
found = true;
} else {
current = current.next;
}
}
return found;
}
The tests are as follows:
public void testContains() {
int size = 10;
Assert.assertEquals(0, list.size());
for (int i = 0; i < size; i++) {
list.insertEnd(i);
}
Assert.assertEquals(size, list.size());
Assert.assertFalse(list.contains(size + 1));
for (int i = 0; i < size; i++) {
Assert.assertTrue(list.contains(i));
}
}
public void testRemoveOnlyElement() {
list.insertEnd(0);
Assert.assertTrue(list.remove(0));
Assert.assertEquals(0, list.size());
Assert.assertNull(list.front());
Assert.assertNull(list.back());
}
@Test
public void testRemoveFirstElement() {
list.insertEnd(0);
list.insertEnd(1);
Assert.assertTrue(list.remove(0));
Assert.assertEquals(1, list.size());
Assert.assertEquals(new Integer(1), list.front());
Assert.assertEquals(new Integer(1), list.back());
}
public void testRemoveMiddleElement() {
list.insertEnd(0);
list.insertEnd(1);
list.insertEnd(2);
Assert.assertTrue(list.remove(1));
Assert.assertEquals(2, list.size());
Assert.assertEquals(new Integer(0), list.front());
Assert.assertEquals(new Integer(2), list.back());
}