[英]How to insert a sorted node into a generic Linked list using java
I have encountered a problem while comparing the generic type data in which the compare to method isn't declared for comparing for example I used this to find the current and previous nodes in which the new node will be inserted between before or after them我在比较泛型类型数据时遇到了一个问题,其中没有声明比较方法用于比较,例如我用它来查找当前和先前的节点,新节点将在它们之前或之后插入
for(prev =null,current = head; current !=null&& newNode.getData().compareTo(current.getData)<0;prev =current,current =current.getNext());
And I tried implementing comparable inside the Node class but I couldn't figure out a way to make it work since it doesn't define the greater than and less than operations.我尝试在节点 class 中实现 comparable ,但我无法找到一种方法使其工作,因为它没有定义大于和小于操作。 `public class LinkedLists1<T> { Node<T> head;
`public class LinkedLists1<T> { Node<T> head;
public LinkedLists1() {
this.head = null;
}
public LinkedLists1(T data) {
Node<T> temp = new Node<T>(data);
head = temp;
}
public void insert(T data) {
Node<T> newNode = new Node<T>(data);
if (head == null) {
head = newNode;
} else {
Node<T> prev = null;
Node<T> current = new Node<T>(head.getData());
implement this for loop
for (prev = null, current = head; current != null
&& newNode.compareTo(current) < 0; prev = current, current = current.getNext());
if (current != null) {
if (head == current) {
newNode.setNext(head);
head = newNode;
} else if (current.getNext() == null) {
current.setNext(newNode);
} else {
newNode.setNext(current.getNext());
current.setNext(newNode);
}
}
}
}
}` }`
So I tried using the compare to method but as I said it's not defined or that's what I got.所以我尝试使用 compare to 方法,但正如我所说,它没有定义,或者这就是我得到的。
Your Node
class needs to properly implement the Comparable
interface.您的
Node
class 需要正确实现Comparable
接口。 Your compareTo()
method inside of the Node class should then look something like this:节点 class 内的
compareTo()
方法应该如下所示:
public int compareTo(Node other) {
return this.data - other.data;
}
Or otherwise be defined such that if this.data
comes before other.data
in the intended ordering then the function returns a negative value.或者以其他方式定义,如果
this.data
按预期顺序出现在other.data
之前,则 function 返回负值。
Edit: compareTo()
is from the Comparable interface, not the Comparator
interface which uses compare()
编辑:
compareTo()
来自Comparable接口,而不是使用compare()
的Comparator
接口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.