题目:已知线性表LA和LB中的数据元素按值非递减有序排列,现要求将LA和LB归并为一个新的线性表LC,且LC中的数据元素仍按值非递减有序排列。例如,设
LA=(3,5,8,11)
LB=(2,6,8,9,11,15,20)
则
LC=(2,3,5,6,8,8,9,11,11,15,20)
线性表见前一章此处用的是线性表的顺序存储结构来实现。
代码:
package com.yds.list; public class JavaMain { private static void MergeList(SequenceList<Integer> listA,SequenceList<Integer> listB,SequenceList<Integer> listC){ //已知线性表La和Lb中的数据元素按值非递减排列 //归并La和Lb得到新的线性表Lc,Lc的数据元素也按值非递减排列 int La_length = listA.length(); int Lb_length = listB.length(); int i = 0,j = 0; while(i<La_length&&j<Lb_length){ if(listA.get(i)<listB.get(j)){ listC.add(listA.get(i)); i++; }else{ listC.add(listB.get(j)); j++; } } while(i<La_length){ listC.add(listA.get(i)); i++; } while(j<Lb_length){ listC.add(listB.get(j)); j++; } } public static void main(String[] args) { // TODO Auto-generated method stub SequenceList<Integer> listA = new SequenceList<Integer>(); SequenceList<Integer> listB = new SequenceList<Integer>(); SequenceList<Integer> listC = new SequenceList<Integer>(); int[] la = {3,5,8,11}; int[] lb = {2,6,8,9,11,15,20}; for (int i = 0; i < la.length; i++) { listA.add(la[i]); } for (int i = 0; i < lb.length; i++) { listB.add(lb[i]); } MergeList(listA,listB,listC); for (int k = 0; k < listC.length(); k++) { System.out.println(listC.get(k)); } } }
结果: