need help with a union function in a linked list

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

    #1

    need help with a union function in a linked list

    Hi!
    Programming language: C
    I wondered if any of you are able to see what is wrong with my code. What I want to do is to find the union of a set of numbers. I use a singly linked list. and my union function is based on a simple merge algorithm.
    There are four different sets: even numbers, odd numbers, prime numbers and non prime numbers.

    When I run my program now, it prints out:
    Even or Odd numbers: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 .. 50 OK!
    Prime or non prime numbers: 48 49
    Even or Prime: 48 50
    Odd or Prime: 49 49

    So apparently the first union(the union of even numbers and odd numbers) works fine, but in the other unions the numbers of the sets are missing...


    could the cause of this be either the head node or the "tail" node?

    [CODE=c]set_t *set_union(set_ t *a, set_t *b) //note:a and b are pointers to sorted sets
    {
    set_t *t; //the merged list`s "tail"
    set_t *h; // the merged list`s head.

    //Find the smallest head node
    if((cmpfunc(a->head->elem, b->head->elem) == -1)){
    t->head = h->head = a->head;
    a->head = a->head->next;
    }
    else {
    t->head = h->head = b->head;
    b->head = b->head->next;
    }

    /* repeatedly pick the smallest head node /*
    while(a->head->next != NULL && b->head->next != NULL) {
    if(cmpfunc(a->head->elem, b->head->elem) == -1){
    t->head->next = a->head;
    t->head = a->head;
    a->head = a->head->next;
    }
    else {
    t->head->next = b->head;

    t->head = b->head;
    b->head = b->head->next;
    }

    }
    /* Append the remaining non-empty list (if any) */
    if(a->head != NULL){
    t->head->next = a->head;
    }
    else {
    t->head->next = b->head;
    }
    return h; //return the head of the merged list

    }[/CODE]

    I am sorry for the long message, but my problem proved to be rather difficult to express with only a few lines.

    please note: *a and *b are pointers to the sets "Even numbers", "odd numbers", "prime numbers", and "non prime numbers"
    And: Cmpfunc is a function that compares the size of object1 and object2.

    Any help is greatly appreciated! Thanks!
    Last edited by Ganon11; Feb 12 '08, 02:36 PM. Reason: Please use the [CODE] tags provided.
  • vekka
    New Member
    • Feb 2008
    • 3

    #2
    Sorry, I forgot to show the struct itself:
    [CODE=c]typedef struct set_node set_node_t;
    struct set_node {
    set_node_t *next;
    void *elem;

    };
    struct set {
    int size;
    set_node_t *head;
    cmpfunc_t cmpfunc;
    };[/CODE]
    Last edited by Ganon11; Feb 12 '08, 03:52 PM. Reason: Please use the [CODE] tags provided.

    Comment

    Working...