-1

所以我实现了这三个类ListNodeLinkedListBook。课本如下:

class Book{
    int price;
    String name;
}

LinkedList包含add()方法(添加一本书)和display(). 我需要向此类添加另一个方法,该方法可以根据书籍名称对包含书籍的列表进行排序。我怎么能这样做,因为我不能使用Collections.sort?这是我所做的方法排序,但我不知道我应该使用什么样的条件来决定是否应该交换元素:

    public void sortList(SortList<Book> l) {

            Node current = head, index = null;
            E temp;
            if (head == null) {
                System.out.println("List is empty");
            } else {
                do {
                    index = current.next;
                    while (index != head) {
//if we had to sort integers would be if(current.data>index.data), then swap
                        if (???) {
                            temp = current.data;
                            current.data = index.data;
                            index.data = temp;
                        }
                        index = index.next;
                    }
                    current = current.next;
                } while (current.next != head);
            }
        }
4

1 回答 1

0

惯用的方法是创建BookComparable,然后比较两个Book实例。如果你不能这样做,你仍然可以提取名称并比较它们,因为Strings 是Comparables:

if (current.data.name.compareTo(index.data.name) > 0) {
    // perform the swap
于 2021-09-12T18:31:07.523 回答