題目:已知線性表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)); } } }
結果: