- #1
heatengine516
Gold Member
- 225
- 18
Homework Statement
Create a SortedLinkedList class which implements the LinkedListInterface.
Remember to use the Comparable class
Basically, I need to implement a sorted linked list that uses generics and uses compareTo to sort objects. I need it to be able to sort names alphabetically. Can't use priorities or indexes.
Homework Equations
n/a
The Attempt at a Solution
My main problem is getting the add() function to work properly. It can sort the head and tail, but it's all the stuff in the middle that is the problem. It won't properly sort anything in the middle between the head and tail. It must be something wrong with my while loop.
Here is my code for the add() function:
public void add(T data ) {
// new node
if (isEmpty()) {
head = new LinkedListNode<T>();
head.data = data;
head.next = tail;
tail = head;
return;
}
if(head.data.compareTo(data) > 0) {
LinkedListNode<T> node = new LinkedListNode<T>();
node.data = data;
node.next = head;
head = node;
return;
}
if(tail.data.compareTo(data) < 0){
tail.next = new LinkedListNode<T>();
tail = tail.next;
tail.data = data;
return;
}
LinkedListNode<T> current = head;
LinkedListNode<T> newNode = new LinkedListNode<T>();
newNode.data = data;
System.out.println(" init: " +data + " < " + current.data);
while (current.data.compareTo(data) < 0 ) {
System.out.println(data + " < " + current.data);
current = current.next;
System.out.println(data + " < " + current.data);
}
newNode.next = current.next;
current.next = newNode;
return;
}
Here is the input:
and here is the output after running:public static void main(String[] args)
{
SortedLinkedList list = new SortedLinkedList();
list.add("jesse");
list.add("rick");
list.add("anne");
list.add("brad");
list.getList();
System.out.println();
list.add("jaime");
list.getList();
}
run SortedLinkedList
init: brad < anne
brad < anne
brad < jesse
anne
jesse
brad
rick
init: jaime < anne
jaime < anne
jaime < jesse
anne
jesse
jaime
brad
rick
I have honestly been working on this for a week and I don't understand why it's not working. I've followed in class examples for our priority and linked queues and online tutorials that are similar but nothing works. Any help would be appreciated. Thank you.