/** * A class to create a linked list in which elements are kept in sorted order. * This is, effectively, doing an insertion sort on this linked list. Sadly, * because this is a linked list, we cannot take advantage of the sort when * searching * * @author gtowell Created: Nov 2020 */ public class SortedDLL> extends DoubleLinkedList { /** * Put new items into the list in sorted order. Note that the conceptsorted * order goes back to the item being added to the list and how it implements he * compareTo method. * * @param t the item to be added */ @SuppressWarnings("unchecked") public void addSorted(Comparable t) { Node newest = new Node<>(t, null, null); // Base case if (head == null) { head = newest; tail = newest; size = 1; return; } // find where to insert Node curr = head; while (curr != null) { if (curr.data.compareTo((T) t) > 0) break; curr = curr.next; } if (curr == null) { // the item become the new end of the list tail.next = newest; newest.prev = tail; tail = newest; } else { // need to put in new node before curr Node tmp = curr.prev; if (tmp != null) tmp.next = newest; newest.prev = tmp; newest.next = curr; curr.prev = newest; if (curr == head) head = newest; } size++; } /** * Override the default addFirst to do addSorted */ @Override public void addLast(Comparable c) { // ???? } /** * Override the default addLast to do addSorted */ @Override public void addFirst(Comparable c) { // ???? } public static void main(String[] args) { SortedDLL llr = new SortedDLL<>(); Rabbit ar = new Rabbit(BreedEnum.Angora, "C1", 2); llr.addSorted(ar); System.out.println(llr); llr.addSorted(new Rabbit(BreedEnum.DwarfDutch, "T1", 3)); System.out.println(llr); llr.addSorted(new Rabbit(BreedEnum.FrenchLop, "M1", 4)); System.out.println(llr); llr.addSorted(new Rabbit(BreedEnum.FrenchLop, "N1", 3)); llr.addSorted(new Rabbit(BreedEnum.FrenchLop, "A1", 2)); llr.addSorted(new Rabbit(BreedEnum.FrenchLop, "Z1", 1)); System.out.println(llr); } }