java有序线性表的有序合并

已知线性表 LA 和 LB 中的数据元素按值非递减有序排列,现要求将 LA 和 LB 归并为一个新的线性表 LC, 且 LC 中的数据元素仍然按值非递减有序排列。例如,设LA=(3,5,8,11) ,LB=(2,6,8,9,11,15,20) 则

LC=(2,3,6,6,8,8,9,11,11,15,20)

输入

有多组测试数据,每组测试数据占两行。第一行是集合A,第一个整数m(0<=m<=100)代表集合A起始有m个元素,后面有m个非递减排序的整数,代表A中的元素。第二行是集合B,第一个整数n(0<=n<=100)代表集合B起始有n个元素,后面有n个非递减排序的整数,代表B中的元素。每行中整数之间用一个空格隔开。

输出

每组测试数据只要求输出一行,这一行含有 m+n 个来自集合 A 和集合B 中的元素。结果依旧是非递减的。每个整数间用一个空格隔开。

样例输入

4 3 5 8 11
7 2 6 8 9 11 15 20

样例输出

2 3 5 6 8 8 9 11 11 15 20
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;


public class Main {
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while(in.hasNext()) {
		int n = in.nextInt();
		ArrayList<Integer> a = new ArrayList<Integer>();
		for (int i = 0; i < n; i++) {
			a.add(in.nextInt());
		}
		int m = in.nextInt();
		ArrayList<Integer> b = new ArrayList<Integer>();
		for (int i = 0; i < m; i++) {
			b.add(in.nextInt());
		}
	    a.addAll(b);
	    Collections.sort(a);//list排序
	    for (Integer aa : a) {
			System.out.print(aa+" ");
		}
	    System.out.println();
		}
		in.close();
		
	}
	
}
发布了81 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41499217/article/details/104378708