【发布时间】:2016-04-06 03:11:25
【问题描述】:
我正在尝试使用插入排序按标题的字母顺序对书的链接列表进行排序。
到目前为止我做了什么:
public void insertSorted(Book book){
if(books.getfirst()==null)
books.addFirst(book); //books is the LinkedList name
Node<Book> current =books.getfirst();
for(int i=0; i<books.getSize(); i++){
if(book.getTitle().compareToIgnoreCase(current.element.getTitle())<=0){
books.add(book, i);
}
}
链表中的add方法:
public void add(Object x,int index){
if(index==0)addFirst(x);
else if(index>=getSize())addLast(x);
else{
Node current=first;
for(int i=0; i<index-1;i++)
current=current.next;
Node temp = new Node(x);
temp.next=current.next;
current.next=temp;
count++;
}
}
我到底做错了什么?
【问题讨论】:
-
在 insertSorted 的 for 循环中,您应该检查 book[i]。 if 语句中的任何内容都不依赖于 i。
-
第一本书重复了两次,是不是循环有问题??
标签: java linked-list insertion-sort