Java資料結構——線性表歸併,java資料結構歸併

來源:互聯網
上載者:User

Java資料結構——線性表歸併,java資料結構歸併

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

結果:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.