Vektor88
Vektor88

Reputation: 4920

Insertion in ordered linked list

I'm trying to insert a node in a linked list so that the nodes are ordered in ascending mode by de idx parameter.

    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;
        }
    }   
}

Edited with correct implementation, the fourth if was missing before.

Upvotes: 0

Views: 637

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361302

It seems correct to me as well, as far as segfault is concerned. However, you don't consider the case when i is greater than the largest number in the list. In this case, you should insert i at the end of the list. So try fixing this bug first, maybe it will fix the segfault as well (which is coming from elsewhere, maybe from your find() implementation).

Now it seems that is the answer (as your comment on my comment confirms it).

Upvotes: 3

Related Questions