2012-02-11 130 views
0

我試圖在鏈表中插入節點,以便通過dex參數以遞增模式對​​節點進行排序。在有序鏈接列表中插入

void add(int i){ 
    if(find(i)==NULL){ //if node does not exist 
     node *m=new node; 
     m->idx=i; 
     m->values=NULL; 
     m->next=NULL; 
     if(list==NULL){ //if list is empty 
      list=m; 
      return;  
     }   
     if(i < list->idx){ //if the new node comes before the head node 
      m->next=list; 
      list=m; 
      return;   
     } 
     //if the new node is bigger than the maximum node index in the list 
     if(i > maxIdx(list)){ 
      node *last=lastNode(list); 
      last->next=m;   
     } 
     //else normal insertion 
     node *prev=list; 
     node *curr=list->next; 
     while(curr!=NULL){ 
      if(i < curr->idx){ 
       m->next=curr; 
       prev->next=m; 
       return;    
      } 
      prev=curr; 
      curr=curr->next; 
     } 
    } 
} 

使用正確的實現進行編輯,第四個如果之前缺少。

+0

這是功課嗎? – 2012-02-11 09:13:47

+0

我是初學者,這不是功課。我能夠做頭部或尾部插入,現在我正在嘗試進行有序插入。 – Vektor88 2012-02-11 09:15:30

+1

'mrow'和'node'之間的關係是什麼? – cnicutar 2012-02-11 09:17:05

回答

3

就segfault而言,對我來說這似乎也是正確的。但是,您不認爲i大於列表中的最大數量的情況。在這種情況下,您應該在列表末尾插入i。因此,請嘗試先修復此錯誤,也許它會修復段錯誤(來自其他地方,可能來自您的find()實施)。

現在看來,這是答案(因爲你對我評論的評論證實了它)。