I'm having issues implementing a merge sort for a linked list, specifically, the merge part. I'm trying to sort a linked list containing strings and sort them alphabetically. However, my merge code sometimes skips pointers for some reason depending on the order of the original list. Currently I have:
public node merge(node left, node right){
node result = null;
if(left == null){
return right;
}else if(right == null){
return left;
}
// The data in the node are stored as strings.
// Compare if the string in the left node is less that
// the string in the right.
if(left.info.compareTo(right.info) < 0){
result = left;
result.next = merge(left.next, right);
}else{
result = right;
result.next = merge(left, right.next);
}
return result;
}
If I had a list that consisted of for example, f->t->c->t->h, my merge will return h->t->t, where pointers are being missed. However, if my list consisted of b->a->t->t->c then it correctly display it alphabetically, a->b->c->t->t, and no pointers are missed.
Any help is appreciated.
Thanks.
LinkedListandCollections.sort(list)to perform that merge sort?