java-双链表的排序方法
作者:互联网
试图弄清楚如何对我的双向链表进行排序.
我在这里得到一个空指针异常:
while (temp.getNext()!=null){
是否有更好的方法或任何建议使此方法正确进行?
public void sort() {
//bubble sort!
boolean swapped = (head != null);
while (swapped) {
swapped = false;
EntryNode temp = head;
//can't swap something with nothing
while (temp.getNext()!=null){
if (temp.getLastName().compareTo(temp.getNext().getLastName()) > 0) {
swapped = true;
//special case for two nodes
if (size == 2) {
//reassign head and tail
tail = temp;
head = temp.getNext();
tail.setPrev(head);
head.setNext(tail);
tail.setNext(null);
head.setNext(null);
}
//if swapping is at head
else {
if (temp == head) {
head = temp.getNext();
temp.setNext(head.getNext());
head.getNext().setPrev(temp);
head.setPrev(null);
head.setNext(temp);
temp.setPrev(head);
}
else {
temp.setNext(temp.getNext().getNext());
temp.setPrev(temp.getNext());
temp.getNext().setNext(temp);
temp.getNext().setPrev(temp.getPrev());
}
}
}
//loop through list
temp = temp.getNext();
}
}
}
解决方法:
使用merge sort算法,通常是best choice,用于对(单个或双重)链接列表进行排序.已经有一个post讨论相关的实施问题.
标签:doubly-linked-list,java,algorithm,sorting 来源: https://codeday.me/bug/20191201/2082115.html