//编写一个交错合并列表元素的函数。例如:给定的两个列表为[a,B,C]和[1,2,3],函数返回[a,1,B,2,C,3]。
private static String[] getStaggeredMergeArray(String[] arr1, String[] arr2)
{ String[] arr = new String[arr1.length + arr2.length];
int i, j; for (i = 0, j = 0; i < arr1.length; i++) {
j = 2 * i;
if (j > 2 * arr2.length)//若arr1数组长度长等于arr2
j = arr2.length + i;
arr[j] = arr1[i];//0 2 4 }
for (i = 0, j = 0; i < arr2.length; i++) {
j = 2 * i + 1;
if (j > 2 * arr1.length)//若arr2数组长度长等于arr1
j = arr1.length + i;
arr[j] = arr2[i];//1 3 5 }
return arr;}
public static void main(String[] args) {
String[] arr1 = { "a", "B", "c", "D", "e" };
String[] arr2 = { "1", "2", "3" };
String[] arr = getStaggeredMergeArray(arr1, arr2);
System.out.println(Arrays.toString(arr));}
- import java.util.*;
- public class Test2{
- public static void main(String[] args){
- ArrayList<Object> a1=new ArrayList<Object>();
- ArrayList<Object> a2=new ArrayList<Object>();
- a1.add('a');
- a1.add('B');
- a1.add('C');
- a2.add(1);
- a2.add(2);
- a2.add(3);
- a1.add(2.2);
- ArrayList<Object> a3=mergeList(a1,a2);
- System.out.println(a3);
- }
- public static ArrayList<Object> mergeList(ArrayList<Object> a1,ArrayList<Object> a2){
- int size=a1.size()+a2.size();
- int j1=0,j2=0;
- ArrayList<Object> a3=new ArrayList<Object>();
- for(int i=0;i<size;i++){
- if(i%2==0)
- a3.add(a1.get(j1++));
- else
- a3.add(a2.get(j2++));
- }
- return a3;
- }
- }