Question

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);
      }
}
Was it helpful?

Solution

There are at least 2 ways:

  1. maintain your linked list in sort order, that way your print code you listed above will just work. This would make insertions take O(n).

  2. If you aren't against using the Java Collection classes during the print part, you can add all your movie titles to a Collection and then sort that (or use a sorted collection which will maintain sort order as you add similar to #1). If you go that route, you will need to implement a Comparator

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top