双链表,current.next=null

iyr7buue  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(324)

做一个家庭作业问题,第一个项目插入到链表插入罚款,当我插入更多的值,他们似乎没有秩序,因为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;    
 }
ztmd8pv5

ztmd8pv51#

在if块中添加'last=newlink',如下所示:

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

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

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

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

3qpi33ja

3qpi33ja2#

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

相关问题