Thursday, January 20, 2011

Merge 2 sorted linked list

In this algorithm, we pick nodes from list q and insert in the right position in the list p.

step 1: foreach node in p (t always follows p, one step behind)
step 2: compare p->info with q->info
step 3: if q<=p, stuff q between p and t, q = q->next, t=q
step 4: else take next node from p and repeat step 2

// takes two linked list and returns pointer to new list
node* merge_sorted_linked_list(node *p, node *q) {

    node *list = p, *temp, *t = null; /* t always trails p */
    
    if( p == NULL )
        return q;
    
    if ( q == NULL )
        return p;
    
    // store the head of resulting list
    if( q->info <= p->info ) 
        list = q; 
        
    while( p && q ) {    
            
        if( q->info <= p->info ) {
            
            // q->next will be changed now
            temp = q->next;
            
            // stuff q between t and p
            if( t != NULL )    t->next = q; 
            q->next = p;
            
            // advance t, now q is a part of the first list
            t = q;    
            
            // q++
            q = temp;            
        } else {
            // advance p, consequently t also
            t = p;
            p = p->next; 
        }    
    }

    if( p == NULL )
        t->next = q;
        
    return list; 
}

No comments :

Post a Comment