I have been having some extreme difficulties with an assignment that I have been given.
The assignment is to create 4 different data structures, LinkedList, DoublyLinked list, deque, and sorted doublylinked list in java. I have almost everything except for the add method in the sorted one.
I have been trying different things for about 4 hours, and every time I do it, the test cases that I have been given fail.
I’m posting my current code, it doesn’t work how I want it to. If anyone can tell by looking at it, what I need to fix, that would be awesome. I can also post code to other methods and other things.
Thank you!
public void add(T item) {
if (head.getData() == null) {
head = new Node(item);
tail = new Node(null);
tail.setPrev(head);
head.setNext(tail);
count++;
} else if (((Comparable<T>) head.getData()).compareTo(item) >=0) {
Node tempNode = head;
head = new Node(item);
head.setNext(tempNode);
tempNode.setPrev(head);
count++;
} else {
Node current = head.getNext();
for (int i = 1; i < size() && current.getData() != null; i++) {
if (((Comparable<T>) current.getData()).compareTo(item) > 0) {
current = current.getNext();
} else if (((Comparable<T>) current.getData()).compareTo(item) <= 0) {
Node newNode = new Node(item);
current.getPrev().setNext(newNode);
newNode.setNext(current);
newNode.setNext(current.getPrev());
current.setPrev(newNode);
count++;
break;
}
}
tail = new Node(item);
current.setNext(tail);
tail.setPrev(current);
count++;
return;
}
}
EDIT ONE:
Okay, I can fix the casts thing, but that won’t exactly help what I’m trying to accomplish. Sorry about the vagueness or unclear parts about my question. It’s slightly difficult to explain.
I was also given a lot of test cases, for example this one:
public void testAddAll() {
SortedDLL<Integer> list = new SortedDLL<Integer>();
assertEquals(0, list.size());
Integer[] objects = {32,0,5125,-12};
Integer[] sorted = {-12,0,32,5125};
list.addAll(objects);
assertEquals(4, list.size());
for (int i = 0; i < objects.length; i++) {
assertEquals(sorted[i], list.get(i));
}
}
When I do this one(using a system.out.println instead of assertEquals) for the last section i got :
(-12, -12)
(0, 0)
(32, 5125)
(5125, 0)
which is not quite right.
I’m just not sure what’s going on. I can’t post all of my tried solutions, because I’ve deleted most of them.
I find your code hard to read and comprehend. It would be nice if you posted your entire class so we know your exact variable definitions etc.
The error I could find in your code’s logic is the following:
This should be changed to something like:
EDIT: The full code has been removed.