【问题标题】:doubly linked list, current.next = null双向链表,current.next = null
【发布时间】:2013-06-06 06:04:49
【问题描述】:

做作业问题,插入链表的第一项插入正常,当我插入更多值时,它们出现乱序,因为根据调试器 current.next 仍然 == null,我不知道为什么我的生活。

public void insert(String key)    
{    
 Link newLink = new Link(key);    
Link current = first;     

 Main.nodeCount++;
 while(current != null && key.compareTo(current.dData) > 0)  
 {              
 if(current.next != null)
 current = current.next;
 else
 break;
 } // end while                                                                                                                                    

 if(isEmpty())
 {
 first = newLink;
 last = newLink;
 return;
 }

 if (current == first )        
 {
 if(key.compareTo(current.dData) < 0)
 {
 newLink.next = current;
 current.previous = newLink;
 first = newLink;
 return;
 }//end if

 if(key.compareTo(current.dData) > 0)
 {
 current.next = newLink;
 first.next = newLink;
 newLink.previous = current;
 return;
 }//end if
 }
 if (current == last)
 {
 if(key.compareTo(current.dData) < 0)
 {
    current.previous.next = newLink;
    newLink.previous = current.previous;
    newLink.next = current;
    current.previous = newLink;
    last = current;
 }

 if(key.compareTo(current.dData) > 0)
 {
    newLink.previous = current;
    current.next = newLink;
    last = newLink;
    return;
 }//end if
 return; 
 }//end if

 if (current != first && current != last)
 {
 current.previous.next = newLink;
 newLink.previous = current.previous;
 newLink.next = current;
 current.previous = newLink;    
 }

【问题讨论】:

  • 原来问题是在当前 == first 语句中添加新链接后没有声明新的最后一个指针,我以某种方式弄乱了顺序。明天我真的睡着了,我会试着找出一个更准确的答案:)

标签: java list pointers null linked-list


【解决方案1】:

在 if 块中添加 'last = newLink' 如下:

if(current == first) {
    ....

    if(key.compareTo(current.dData) > 0) {

        last = newLink;
        ....
    }
    ....
}

这是必需的,因为如果控件转到 if 块,则当前是最后一个链接。否则,在上面的 while 循环完成后,当前将是当前右侧的另一个链接。

【讨论】:

    【解决方案2】:
    if(isEmpty())
    {
       first = newLink;
       first.next = NULL;  //need to initialize next and prev pointers 
       first.prev = NULL;
    
       last = first;
       return;
    }
    
    if (current == first )        
     {
      if(key.compareTo(current.dData) < 0)
      {
      newLink.next = current;
      current.previous = newLink;
      first = newLink;
      return;
      }//end if
    
      if(key.compareTo(current.dData) > 0)
      {
      current.next = newLink;
      // first.next = newLink;   --> redundant
      newLink.previous = current;
      newlink.next = NULL;
      last = newLink   -->
      return;
      }//end if
    

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 1970-01-01
      • 2013-11-15
      • 2019-06-03
      • 2015-03-24
      • 2015-04-04
      • 2021-11-18
      • 2012-06-25
      相关资源
      最近更新 更多