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;
}
}
CodePudding user response:
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;