2013-06-06 97 views
0

做一個家庭作業問題,插入到鏈接列表中的第一項插入罰款,當我插入更多的值,他們出現亂序,因爲current.next根據調試器保持== null,我無法弄清楚爲什麼我的生活。雙向鏈接列表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;  
} 
+0

原來問題是在當前==第一條語句中添加新鏈接後沒有聲明新的最後一個指針,我以某種方式搞亂了順序。我明天會試着找出一個更準確的答案,當我真的睡了:) – NoobException

回答

0

添加「LAST = NEWLINK」中,如果塊如下:

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

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

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

這是必需的,因爲如果控制進入,如果塊,那麼當前是最後一個環節。否則,在完成上面的while循環時,當前將是當前右邊的另一個鏈接。

0
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