2013-06-06 67 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