Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent conflicting parameters?

I got a function that takes two lists. For example, list1 = [1, 2] and list2 = [3, 4], the function merges them together into list1 = [1, 2, 3 ,4], leaving list2 empty. But now, I’m trying to make the function do nothing when it takes in the same list. For example, both *a and *b are passed as list1. How I do that?

typedef struct node {
    ElemType val;
    struct node *next;
} NODE;

struct list_struct {
    NODE *front;
    NODE *back;
};

void merge(LIST *a, LIST *b) {
    if (a->front != NULL || b->front != NULL) {
        a->back->next = b->front;
        a->back = b->back;
        b->front = NULL;
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Just check the parameters and act accordingly, for example like this:

void merge(LIST *a, LIST *b) {
    if (a == b) {
      // do nothing, or whatever...
    }
    else
    {
        if (a->front != NULL || b->front != NULL) {
            a->back->next = b->front;
            a->back = b->back;
            b->front = NULL;
        }
    }
}

But beware: with your code, a will contain all elements from b after a merge, but if you now remove elements from b, these now inexistent elements will still be referenced by a and you have a problem.

IOW: your merge function works, as long as you never remove elements from lists you have merged from.

Are you sure this is what you want?

BTW: you forgot the ytepdef for LIST:

typedef struct list_struct {
    NODE *front;
    NODE *back;
} LIST;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading