Write a method called alternate that accepts two Lists of in

Write a method called alternate that accepts two Lists of integers as its parameters and returns a new List containing alternating elements from the two lists, in the following order: First element from first list First element from second list Second element from first list Second element from second list Third element from first list Third element from second list ... If the lists do not contain the same number of elements, the remaining elements from the longer list should be placed consecutively at the end. For example, for a first list of (1, 2, 3, 4, 5) and a second list of (6, 7, 8, 9, 10, 11, 12), a call of alternate(listl, list2) should return a list containing (1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 11, 12). Do not modify the parameter lists passed in. Type your solution here: public static List alternate(List list1, List list2) {}

Solution

public static List<Integer> alternate(List<Integer> list1,List<Integer> list2)

{

List<Integer> list3= new ArrayList<Integer>();

int j=1;

int len=list1.size()+list2.size();

int l1=0,l2=0;

for(int i=1;i<=len;i++)

{

if(i%2==1){

list3.add(list1.get(l1));

l1++;

}

else

{

list3.add(list2.get(l2));

l2++;

}

}

return list3;

}

 Write a method called alternate that accepts two Lists of integers as its parameters and returns a new List containing alternating elements from the two lists,

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site