2012-02-11 133 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()实施)。

现在看来,这是答案(因为你对我评论的评论证实了它)。