I’m trying to append two structures into one
Ex.
l1 = add(1, add(2, NULL));
l2 = add(3, add(4, NULL));
myappend(l1,l2) = add(1,add(2,add(3,add(4,NULL))))
I tried many other ways that I can think of… but it doesn’t work… can anyone help me out?
struct list_node {
struct list_node * rest;
int first;
};
list add(int in, list l) {
list r = malloc(sizeof(struct list_node));
r->first = in;
r->rest = l;
return r;
}
// My attempted solution;
list myappend(list l1,list l2){
list k = malloc(sizeof(struct list_node));
k=l2;
k=add(l1,k);
return k;
}
I guess the type
listisstruct list_node *. If you can define a type forlist, you can define a type forlistwith alastpoint to the last node of the list, example:If you want to keep the type
listasstruct list_node *, you should1) Ensure the last node(of a list)’s
restis NULL.2) Loop and find the last node of the fist list and do the merge(just link them).
You can also use recursion code: