简体   繁体   中英

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. `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.

Your Node class needs to properly implement the Comparable interface. Your compareTo() method inside of the Node class should then look something like this:

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.

Edit: compareTo() is from the Comparable interface, not the Comparator interface which uses compare()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM