我一直在努力让我的冒泡排序工作,现在它似乎陷入无限循环。
我以为我正在适当地增加指针以照顾它,但似乎没有。如果有人能够发现我的增量器应该去哪里使它适当地退出那就太棒了!
bubblesort方法:
public static void bubbleSort(DoubleLinkedList list) //static method used to sort the linked list using bubble sort
{
int i = 0;
int j = 0;
Node currentNode = list.head;
Node previousNode = currentNode;
Node tempNext = currentNode;
Node tempPrevious = currentNode;
Node sentinelNode = currentNode;
for(i=1; i<list.getSize(); i++)
{
while(sentinelNode.getNext() != null)
{
if(currentNode.getData() > currentNode.getNext().getData())
{
if(currentNode == list.head)
{
Node tempNode = currentNode.getNext();
list.head = tempNode;
tempNext = tempNode.getNext();
tempNode.setNext(currentNode);
currentNode.setNext(tempNext);
currentNode.setPrevious(tempNode);
tempNext.setPrevious(currentNode);
}
else if(currentNode.getNext() == list.last)
{
Node tempNode = currentNode.getNext();
list.last = currentNode;
tempPrevious = currentNode.getPrevious();
tempNode.setNext(currentNode);
tempNode.setPrevious(tempPrevious);
currentNode.setPrevious(tempNode);
}
else
{
Node tempNode = currentNode.getNext();
tempPrevious = currentNode.getPrevious();
tempNext = currentNode.getNext();
tempPrevious.setNext(tempNode);
tempNext.setPrevious(currentNode);
currentNode.setNext(tempNext);
tempNode.setPrevious(tempPrevious);
}
}
sentinelNode = sentinelNode.getNext();
}
}
}
答案 0 :(得分:0)
您的问题出在您的else子句中。仔细看看你的设置。首先,你有,
tempNode = currentNode.getNext();
tempNext = currentNode.getNext();
他们指向同一个对象。当你这样做时
currentNode.setNext(tempNode);
您没有更改任何内容,因为tempNode已经是current.getNext();
正因为如此,你的sentinelNode在迭代DoubleLinkedList时遇到了问题。