如何使我在 Java 中的自定义泛型类型链表排序?
我正在用泛型类型的 java 编写自己的链表,而不是使用 java 集合链表.链表的add方法由以下代码组成:
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 following code:
public void add(T item, int position) {
Node<T> addThis = new Node<T>(item);
Node<T> prev = head;
int i;
if(position <= 0) {
System.out.println("Error: Cannot add element before position 1.");
}
else if(position == 1) {
addThis.setNext(head);
head = addThis;
} else {
for(i = 1; i < position-1; i++) {
prev = prev.getNext();
if(prev == null) {
System.out.println("Cannot add beyond end of list");
}
} // end for
addThis.setNext(prev.getNext());
prev.setNext(addThis);
}
} // end add
我将如何做到这一点,以便当我添加一个新项目时,将该项目与另一个项目进行比较并按字母顺序插入?我已经研究过使用 compareTo,但我不知道该怎么做.
How would I make it so that when I add a new item, the item is compared to another item and is inserted alphabetically? I have looked into using compareTo but I cannot figure out how to do it.
谢谢
我有各种类:我有一个名为 Dvd 的类,它具有标题(字符串)和数量的方法和变量该标题的副本(int).我还有一个 链表类,一个 listinterface、一个节点类和一个主类.
I have various classes: I have a class called Dvd which has methods and variables for a title(string) and number of copies of that title(int). I also have a linked list class, a listinterface, a node class, and a main class.
推荐答案
我终于用插入排序搞定了:
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);
}
}
相关文章