How would I make my custom generic type linked list in Java sorted?

后端 未结 3 1871
温柔的废话
温柔的废话 2021-01-24 23:44

I am writing my own linked list in java that is of generic type instead of using the java collections linked list. The add method for the linked list is made up of the followi

3条回答
  •  迷失自我
    2021-01-24 23:56

    I finally figured it out by 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);
          }
    }
    

提交回复
热议问题