Java 插入排序中的交换在双链接列表中不起作用
此插入排序属于双链接列表。它似乎没有打印出任何内容。对不起,这太乱了。我对张贴东西相当陌生。我通过输入sysout调试了它。我相信我使用sysout的交换有问题&我注意到这就是问题发生的地方。任何帮助都将不胜感激。我还检查了我的应用程序类,看起来不错Java 插入排序中的交换在双链接列表中不起作用,java,doubly-linked-list,insertion-sort,Java,Doubly Linked List,Insertion Sort,此插入排序属于双链接列表。它似乎没有打印出任何内容。对不起,这太乱了。我对张贴东西相当陌生。我通过输入sysout调试了它。我相信我使用sysout的交换有问题&我注意到这就是问题发生的地方。任何帮助都将不胜感激。我还检查了我的应用程序类,看起来不错 public boolean insertionSort() { if (getFirst().next != null) { return false; } Link current = getFirst().next; Link
public boolean insertionSort()
{
if (getFirst().next != null)
{
return false;
}
Link current = getFirst().next;
Link current2 = current;
while(current != null){
current2 = current;
while(current2.prev != null){
int tempID = Integer.valueOf(current2.Data.getID());
int temp2ID = Integer.valueOf(current2.prev.Data.getID());
if(tempID < temp2ID )
{
swap(current2, current.prev);
}
current2 = current2.prev;
}
current = current.next;
}
return true;
}
public void swap(Link x, Link y)
{
Link previousNode1 = x.prev;
Link nextNode1 = x.next;
Link previousNode2 = y.prev;
Link nextNode2 = y.next;
if (x.next == y || y.next == x)
{
previousNode1.next = y;
y.prev = (previousNode1);
nextNode2.next = (x);
x.next = (nextNode2);
x.prev = (y);
y.next = (x);
}
else
{
y.prev = (previousNode1);
y.next = (nextNode1);
nextNode1.prev = (y);
previousNode1.next = (y);
x.prev = (previousNode2);
x.next = (nextNode2);
nextNode2.prev = (x);
previousNode2.next = (x);
}
} // end swap
public boolean insertionSort()
{
if(getFirst().next!=null)
{
返回false;
}
链接当前=getFirst()。下一步;
链路电流2=电流;
while(当前!=null){
电流2=电流;
while(current2.prev!=null){
int tempID=Integer.valueOf(current2.Data.getID());
int temp2ID=Integer.valueOf(current2.prev.Data.getID());
if(tempID
您只给出了部分代码。所以很难找出到底是什么错了。但是,乍一看insertionSort方法,这就是问题所在:在一开始,您有一个条件语句
if (getFirst().next != null){
return false;
}
这意味着如果getFirst(),函数将立即返回。next为非null。如果程序流满足此条件,即getFirst().next为null,则将此null分配给两个变量current和current2。然后运行一个while循环,条件是while(current!=null){…}
。这个函数应该怎么做
首先,纠正if条件。可能仅当getFirst().next为null时才需要返回(如果不是null,则不返回)。然后,看看你是否得到了你想要的输出。如果没有,请详细说明您的问题