Answer:
Explanation code is given below along with step by step comments!
Step-by-step explanation:
// first we create a function which accepts two ArrayList of integers named list1 and list2
public static void interleave(ArrayList<Integer> list1, ArrayList<Integer> 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]