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?
Expand|Select|Wrap|Line Numbers
- 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
- }
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!