Ask Question
9 August, 10:49

Write a program called interleave that accepts two ArrayLists of integers list1 and list2 as parameters and inserts the elements of list2 into list1 at alternating indexes. If the lists are of unequal length, the remaining elements of the longer list are left at the end of list1.

+5
Answers (1)
  1. 9 August, 14:17
    0
    Explanation code is given below along with step by step comments!

    Explanation:

    / / first we create a function which accepts two ArrayList of integers named list1 and list2

    public static void interleave (ArrayList list1, ArrayList list2)

    {

    / / we compare the size of list1 and list2 to get the minimum of two and store it in variable n

    int n = Math. min (list1. size (), list2. size ());

    int i;

    / / here we are getting the elements from list2 n times then we add those elements in the list1 alternating (2*i+1)

    for (i = 0; i < n; i++)

    {

    int x = list2. get (i);

    list1. add (2 * i + 1, x);

    }

    / / if the size of list1 and list2 is same then program stops here else we need to append extra elements at the end of list1

    / / then we check if the size of list2 is greater than list1 then simply add the remaining elements into list1

    if (i < list2. size ())

    {

    for (int j = i; j < list2. size (); j++)

    {

    list1. add (list2. get (j));

    }

    }

    }

    Sample Output:

    list1=[1, 2, 3]

    list2=[5, 6, 7, 8, 9]

    list1=[1, 5, 2, 6, 3, 7, 8, 9]
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a program called interleave that accepts two ArrayLists of integers list1 and list2 as parameters and inserts the elements of list2 ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers