首页 > 代码库 > 数据结构单列表的合并实现

数据结构单列表的合并实现

package com.he.list;

public class Collections {

	public static ArrayList union(ArrayList l1, ArrayList l2) {
		int l2_length = l2.getLength();
		for (int i = 0; i < l2_length; i++) {
			if (!l1.contains(l2.get(i))) {
				l1.add(l2.get(i));
			}

		}
		return l1;
	}

	public static void main(String[] args) {
		ArrayList l1 = new ArrayList();
		ArrayList l2 = new ArrayList();
		for (int i = 0; i < 20; i++) {
			if (i < 10) {
				l1.add(i);
			}
			l2.add(i);

		}

		System.out.println("这是列表1:");
		for (int i = 0; i < l1.getLength(); i++) {
			System.out.print(l1.get(i) + " ");
		}
		System.out.println();
		System.out.println("这是列表2:");
		for (int i = 0; i < l2.getLength(); i++) {
			System.out.print(l2.get(i) + " ");
		}

		l1 = Collections.union(l1, l2);
		System.out.println();
		System.out.println("合并俩个列表:");
		for (int i = 0; i < l1.getLength(); i++) {
			System.out.print(l1.get(i) + " ");
		}
	}
}
ArrayList的实现请参考上篇博文,更多内容请关注小猿公众号:love_coding