Wow! You've obviously put a lot of work into this!
#Advice / Optimizations#
- Unless it's an explicit requirement of the assignment, there's no reason you can't use
java.util.LinkedList.
- I think it's cleaner to have the
mergeLinkedLists method live in a different class from the linked list. In other words, the linked list is a completely reusable container for data, and the customizations live somewhere else.
- If you want to get fancy you can use generics so that this class can operate on any
Object, not just Integer. (This should be considered "extra credit," not a critique of your program.)
This is how I would write it. (This is likely a school assignment so I'm just supplying a skeleton.)
public class Merge {
private Merge() { } // no public constructor
public static List<Integer> merge(List<Integer> list1, List<Integer> list2) {
List<Integer> returnVal = new LinkedList<>();
if (list1 == null && list2 == null) {
// both lists null. What to return? Or throw exception.
}
if (list1 == null) {
// What to return? Or throw exception.
}
if (list2 == null) {
// What to return? Or throw exception.
}
// do merging
while (list1.isEmpty() && !list2.isEmpty()) {
// We know that both lists must have at least one element.
// 1. Figure out which list has the smaller element.
// 2. Remove that item from its list.
// 3. Add that item to the end of returnVal
}
// Now one or both lists are empty.
// Those items have to be added to "returnVal" as well.
return returnVal;
}
public static List<Integer> mergeRecursive(List<Integer> list1, List<Integer> list2) {
// do stuff
}
}
#Stupid Picky Stuff#
- You don't need to have a name like
mergeLinkedListRecursion if the parameter is already of type LinkedList. You can just call it mergeRecursion. Anybody reading it will understand that it operates on linked lists.
- I don't get why you have functions with names of "recursive", "recursion", and "recurse". It seems to me it would be cleaner to use one verb form for all your functions.