Merge algorithm

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vekka
    New Member
    • Feb 2008
    • 3

    #1

    Merge algorithm

    Hi!
    Could someone please help me to understand the use of merge algorithm(conce ptually) with linked lists. What I want to do in the linked list function is:
    the function gets two inputs, i.e the pointers to the two smaller lists, then the function should able to merge these two together, and then return the head-pointer to this merged list. What happens in my case, is that I "lose" data when running it . My result is like this:

    Even OR Odd numbers: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... 50 OK
    Prime OR non Prime numbers: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15... OK
    Even OR Prime numbers: 48 49 What happened here?
    Odd OR Prime numbers: 49

    Some sort of "Pseudocode ":

    Code:
    set_t *set_union(set_t *a, set_t *b) {
    
       set_node_t *head, *tail  (<---pointers to nodes)
      
       if (a < b) 
        head = tail = a->head
        a->head = a->head + 1
    
       if (a > b)
        head = tail = b->head
        b = b + 1
    
        while( a < end && b < end)
           if( a < b )
          tail->next = a->head
          a->head = a->head->next
    
          else
           tail->next = b->head
           b->head = b->head->next
         
           if b was exhausted before a
           if ( a->head != NULL)
               tail->next = a->head->next
    
           vice versa
           if(b->head != NULL) 
           tail->next = b->head->next
    
    
          return head
    Will not this code actually return a merged list? or am I doing something wrong with the pointers? Thanks in advance!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    A merge usually is a sorted merge of two lists.

    you would
    1) append the list to be merged to the final list.
    2) sort the final list.
    3) delete the list to be merged

    Comment

    Working...