【问题标题】:Swap In Insertion Sort Not Working In a Doubly Link List交换插入排序在双向链表中不起作用
【发布时间】:2016-04-16 00:08:42
【问题描述】:

这种插​​入排序属于双向链表。它似乎没有打印出任何东西。抱歉,如果这很混乱。我对发布东西还很陌生。我已经通过放入 sysout 对其进行了调试。我相信我使用 sysout 的交换存在问题,我注意到这就是问题发生的地方。任何帮助将不胜感激。我还检查了我的应用程序类,看起来不错。

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

【问题讨论】:

    标签: java doubly-linked-list insertion-sort


    【解决方案1】:

    您只提供了一部分代码。所以很难弄清楚到底是什么问题。但乍一看您的 insertSort 方法,这是错误的:一开始您有一个条件语句

    if (getFirst().next != null){
       return false;
    }
    

    这意味着如果 getFirst().next 为 not null,该函数将立即返回。如果程序流程满足此条件,即 getFirst().next 为 null,则将此 null 分配给两个变量 current 和 current2。然后运行一个带有条件while(current != null){...} 的while 循环。这个函数应该怎么做?

    首先,更正 if 条件。可能只有当 getFirst().next 为空时才需要返回(如果不为空则不返回)。然后,看看你是否得到了你想要的输出。如果没有,请详细说明您的问题。

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2022-11-16
      • 2019-07-23
      • 2018-12-25
      相关资源
      最近更新 更多