花了几个小时试图让冒泡排序的实现在双链表上工作。我的代码似乎可以通过一次,但在没有完成排序的情况下过早完成。任何指导将不胜感激。
public void bubbleSort()
{
Node cur = head.getNext();
boolean done = false;
while (!done)
{
done = true;
while(cur != tail)
{
if (cur.getNext().getCount()>cur.getCount())
{
swap(cur.getNext(),cur);
done=false;
}
cur = cur.getNext();
}
}
}
我使用的交换方法似乎破坏了节点的放置,直到它成为两个节点之间的循环。
private void swap(Node n1, Node n2)
{
Node b1, b2, a1, a2;
System.out.println("Swapping n1: " + n1 + " with n2: " + n2);
b1 = n2.getPrev();
if (b1 == n1) // handle adjacent nodes
b1 = n2;
a1 = n2.getNext();
b2 = n1.getPrev();
if (b2 == n2) // handle adjacent nodes
b2 = n1;
a2 = n1.getNext();
// swap
n1.setPrev(b1);
n1.setNext(a1);
n2.setPrev(b2);
n2.setNext(a2);
b1.setNext(n1);
a1.setPrev(n1);
b2.setNext(n2);
a2.setPrev(n2);
}
谢谢