How would I make my custom generic type linked list in Java sorted?(如何使我在 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);
}
}
这篇关于如何使我在 Java 中的自定义泛型类型链表排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使我在 Java 中的自定义泛型类型链表排序?


- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01