I need to implement some divide-and-conquer algorithms (binary search, merge sort, etc) using linked lists.
To do this, I need to define a method that divides a certain list into two, so that the size difference between them is a maximum of 1 element.
That's my structure:
typedef struct linked_list *L;
typedef struct linked_list{
int info;
L next;
};
L
is a pointer to a linked_list
.
The code below is my algorithm attempt that splits the given list into front and back halves.
I couldn't think of a way to return two generated lists, so I pass two empty lists as parameters.
void split_list(L r, L front, L back){
L a = r->next;
L b = r;
while( a ){
a = a->next;
if ( a->next ){
a = a->next;
b = b->next;
}
}
back = b->next;
front = r;
b->next = NULL;
}
However, when you run the function on the main, it does not work as expected.
L z = NULL;
/ insert some nodes in z /
L x = NULL;
L y = NULL;
split_list(z, x, y);
Trying to print x
and y
, they are empty (apparently).
I believe the problem is in the way that the lists are passed as a parameter, but I don't know exactly how to solve this.