I created a generic linked list in java (not the built in one) and have a LinkedList class, ListInterface class, Node class, a Dvd class and a DvdManager class. My goal is to be able to add Dvd's to the linked list and print them out alphabetically. I have successfully been able to write the code to add, remove, and add copies of Dvd's to the linked list. However, I cannot figure out how to print the list alphabetically. I can print the list using the following code, but it does not print alphabetically based on the title of the item:
if (movies.isEmpty()) {
System.out.println("The list is empty.");
} else {
for (int i = 1; i <= movies.length(); i++) {
System.out.println(movies.get(i).getTitle());
}
}
How would I get the generic type list to print alphabetically?
Here are my class files if you want to take a look (I put them on pastebin because they're long):DvdManager, Dvd, LinkedList, ListInterface, and Node.
Thanks.
Edit:
I figured it out using an insertion sort:
public void add(Dvd item) {
DvdNode addThis = new DvdNode(item);
if(head == null) {
head = addThis;
} else if(item.getTitle().compareToIgnoreCase(head.getItem().getTitle()) < 0) {
addThis.setNext(head);
head = addThis;
} else {
DvdNode temp;
DvdNode prev;
temp = head.getNext();
prev = head;
while(prev.getNext() != null && item.getTitle().compareToIgnoreCase
(prev.getNext().getItem().getTitle()) > 0) {
prev = temp;
temp = temp.getNext();
}
addThis.setNext(temp);
prev.setNext(addThis);
}
}