Skip to content
Advertisement

Comparing two linked lists and returing a list with maximum values

I am planning to write a Java Function that takes two linked lists. Both have the same size. I want to return a new list that contains the maximum of the data found in the corresponding nodes of the two lists passed to my function.

However I am stuck in filling the new list. I came up with this:

function max2List (LinkedList list1 , LinkedList list2) {
    LinkedList <int> list3 = new LinkedList<int> ();
    for (ListNode p = list1.first ; p!=null; p=p.next) {
        for (ListNode p = list2.first ; p!=null; p=p.next) {
            if (list1.p.data > list2.p.data ) {
                //return list3 here with big value
            else if (list1.p.data < list2.p.data ) {
               //return list3 here with big value

I don’t know how to continue. I want list3 to contain the maximum values from the two lists.

Advertisement

Answer

Firstly, what you have written is not valid Java. Generics cannot use primitive types, such as the use of <int> in your example. It needs to be a class e.g. <Integer>. function is also not a keyword.

For brevity, the following code assumes both lists are of equal size:

public static List<Integer> max2List (List<Integer> list1, List<Integer> list2)
{
    List<Integer> maxValues = new LinkedList<>();

    for (int i = 0; i < list1.size(); ++i)
    {
        // If item in list1 is larger, add it
        if (list1.get(i).compareTo(list2.get(i)) > 0)
        {
            maxValues.add(list1.get(i));
        }
        else // else add the item from list2
        {
            maxValues.add(list2.get(i));
        }
    }

    return maxValues;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement