我在java中有这个自定义链表(不是java集合LinkedList)。它将项目添加到列表中的选定位置。
public void add(T item, int position) {
Node<T> addThis = new Node<T>(item);
Node<T> prev = head;
int i;
if(position <= 0) {
//throw new ListException("Cannot add element before position 1");
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) {
//throw new ListException("Cannot add beyond end of list");
System.out.println("Cannot add beyond end of list");
}
} // end for
addThis.setNext(prev.getNext());
prev.setNext(addThis);
}
} // end add
我想要做的不是在选定位置添加项目,而是希望按字母顺序添加项目,以便整个列表在插入时按字母顺序排序。这是我到目前为止的代码,但我被卡住了。我怎样才能让它做我想做的事?
public void add(String title) {
DvdNode addThis = new DvdNode(title);
if (head == null) {
head = addThis;
} else if(title.compareToIgnoreCase(head.getTitle()) < 0) {
// title comes before the current, so add as the first Dvd in the list
} else {
// the new title belongs somewhere later in the list
// while i less than size of the list compare and insert if its greater
// than what its being compared to
// also update the links for the list so the whole list is still accessible
}
}
编辑:我终于让它工作了。我的解决方案基于 Byakuya 的解决方案。
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);
}
}