使用Java以升序将节点添加到列表中

时间:2018-02-13 06:23:10

标签: java linked-list

有没有办法在比较对象时使用compareTo函数,我不确定它是否只适用于字符串。我正在尝试按升序将节点添加到正确的位置。

继承人我声明我的属性/构造函数

private Node<E> head; //refers to the head of the node
private int size; // keeps track of the size of the list

// default constructor which creates empty ordered list
public OrderedList(){head = null; size = 0;}

继承我的插入功能

public void insert(Object o)
{
    Node n = new Node(o, null); // creates new node
    // Node for first element greater than or equal
    Node current = head.getLink();
    Node before = head; // Node for right before the next one is found

    // checks to see if list is empty
    if(size == 0)
    {
        head = n;
    }
    // checks if element is smaller than the head
    else if (o.compareTo(head.o) < 0) 
    {
        n.getLink() = head;
        head = n;
    } 
}

这是我的节点类

package project.pkg3;

public class Node<T> 
{
private Object data;
private Node link;

public Node(Object o, Node l){data = o; link = l;}

public void setData(Object o){data = o;}
public void setLink(Node l){link = l;}

public Object getData(){return data;}
public Node getLink(){return link;}


}

我在尝试检查该元素是否属于此行的前面时收到错误消息

  else if (o.compareTo(head.o) < 0) 

告诉我它找不到符号,我不知道这意味着什么

我还在这一行收到了另一条错误消息

  n.getLink() = head;

这个告诉我这是一个意想不到的类型

2 个答案:

答案 0 :(得分:0)

您的节点类应该实现java.lang.Comparable接口并根据您的逻辑覆盖其compareTo()方法。

public class Node<T extends Comparable<T>>{

}

您的参数对象将实现Comparable接口。例如:

public class Name implements Comparable<Name> {
  private String str1;

  public int compareTo(Name o) {
    //your logic here to compare object with itself
    return this.str1.compareTo(o.str1);
  }
}

答案 1 :(得分:0)

如果必须使用compareTo()对链接列表进行排序,则需要确保基础数据具有可比性。

public class Node<T extends Comparable> 
{
    private T data;
    private Node<T> link;

    public Node(T o, Node<T> l) { data = o; link = l; }

    public void setData(T o) { data = o; }
    public void setLink(Node<T> l) {link = l; }

    public T getData() { return data; }
    public Node<T> getLink() { return link; }
}

然后这个块

else if (o.compareTo(head.o) < 0) 
{
    n.getLink() = head;
    head = n;
}

应改为:

else if (
    (o.getData() != null) ?
    (o.getData().compareTo(head.getData()) < 0) :
    (head.getData().compareTo(o.getData()) > 0)
    ) 
{
    n.setLink(head);
    head = n;
}

我没有查看你的链表实现,所以我不知道其他的东西是否正确。

相关问题