I wrote mergesort() in C++ for linked lists. The issue is that my professor has provided test code with a very large list (length of 575,000). This causes a stack overflow error for my function since it is written recursively.
So it's possible my professor expects us to write it using iterations instead of recursion. I wanted to ask if there is anything wrong with my code that may be causing the stack to overflow?
My code:
typedef struct listnode {
struct listnode * next;
long value;
} LNode;
LNode* mergesort(LNode* data) {
if(data == NULL || data->next == NULL) {
return data;
}else {
LNode* s = split(data);
LNode* firstSortedHalf = mergesort(data);
LNode* secondSortedHalf = mergesort(s);
LNode* r = merge(firstSortedHalf, secondSortedHalf);
return r;
}
}
LNode* split(LNode* list) {
if(list) {
LNode* out = list->next;
if(out) {
list->next = out->next;
out->next = split(out->next);
}
return out;
}else {
return NULL;
}
}
LNode* merge(LNode* a, LNode* b) {
if(a == NULL)
return b;
else if(b == NULL)
return a;
if(a->value < b->value) {
a->next = merge(a->next,b);
return a;
}else {
b->next = merge(a, b->next);
return b;
}
}
mergesort()for linked lists, so recursion only felt most natural.