public Link insert(String data, int where)
{
Link temp = first;
//If list is empty, insert as first
if (first == null)
{
first = new Link(data, where);
return first;
}
//List is not empty
else
{
while (temp != null)
{
//If data is less than first, then insert as first
if (data.compareTo(temp.getdData()) < 0 && temp == first)
{
Link newLink = new Link(data, where);
newLink.setNext(first);
first.setPrevious(newLink);
first = newLink;
return newLink;
}
//If data is less than current, then insert before current
else if (data.compareTo(temp.getdData()) < 0)
{
Link newLink = new Link(data, where);
newLink.setNext(temp);
newLink.setPrevious(temp.getPrevious());
temp.getPrevious().setNext(newLink);
temp.setPrevious(newLink);
return newLink;
}
//If data is more, but your at the end of the list.
else if (data.compareTo(temp.getdData()) > 0 && temp.getNext() == null)
{
Link newLink = new Link(data, where);
temp.setNext(newLink);
newLink.setPrevious(temp);
newLink.setNext(null);
last = newLink;
return newLink;
}
//Else keep going forward
else
temp = temp.next;
}
}
return temp;
}
我可以插入列表中,但出于某种原因,它不会按顺序插入。例如,如果链接的数据是&#34; Hello&#34;我想在&#34; aaa&#34;中插入一个链接,它不会在&#34; Hello&#34;之前插入新链接。链接。
答案 0 :(得分:0)
看看java比较字符串的方式:
java> "aaa".compareTo("Hello") // positive number
java> "Aaa".compareTo("Hello") // negative number
原因是字符'a'的ASCII码大于'H'。
顺便说一句,你最好在你的代码中使用.equals()而不是==来比较Java中的String,看一下这个链接: http://perso.ensta-paristech.fr/~diam/java/online/notes-java/data/expressions/22compareobjects.html答案 1 :(得分:0)
如果你重新实现集合 - 那就是你做错了什么的红旗。
您的任务可以更简单地解决:
public class Link {
private final String data;
private final int where;
...
}
public class LinkComparator implements Comparator<Link> {
@Override
public int compare(Link o1, Link o2) {
return o1.data.compareToIgnoreCase(o2.data);
}
}
public static void main(String[] args) {
NavigableSet<Link> links = new TreeSet<Link>(new LinkComparator());
links.add(new Link(...));
}