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 中的自定义泛型类型链表排序?


基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01