java實現順序鏈表

來源:互聯網
上載者:User

標籤:

SequenceList.java檔案

package list;public class SequenceList {private int LIST_INIT_SIZE = 5;//鏈表的原始大小private int INCREMENT =1;//鏈表的增量大小private Object []SqList = null;//鏈表private int curIndex=0;//當前位置/** * 初始化鏈表 * */public void initList(){SqList = new Object[LIST_INIT_SIZE];}/** * 向鏈表中插入元素 * */public void insertList(Object o){if(curIndex>LIST_INIT_SIZE-1)//判斷當前鏈表是否已經滿{//從新為鏈表分配空間System.out.println("從新分配空間");LIST_INIT_SIZE+=INCREMENT;Object []temp = new Object[LIST_INIT_SIZE];for(int i=0;i<curIndex;i++){temp[i]=SqList[i];}SqList=null;SqList=temp;}//鏈表中如果不讓其包含重複元素,則加入這段代碼/*if(isContain(o)){System.out.println("鏈表中已包含此元素"+o);}else{}*/SqList[curIndex++]= o;}/** * 判斷鏈表中是否包含某元素 * */Boolean isContain(Object o){for(int i=0;i<curIndex;i++){if(SqList[i].equals(o)){return true;}}return false;}/** * 刪除鏈表中的某元素 *  * 如果包含重複元素都刪除 * */public void delete(Object o){for(int i=0;i<curIndex;i++){if(SqList[i].equals(o)){for(int j=i;j<curIndex-1;j++){SqList[j]=SqList[j+1];}curIndex--;continue;}if(i==curIndex-1){System.out.println("不存在此元素"+o);}}}/** * 擷取鏈表中的某個元素 * */public Object getElement(int i){if (i <= 0 || i > curIndex) {System.out.println("擷取位置超出了鏈表中元素個數"+curIndex);}return SqList[i-1];}/** * 列印鏈表 * */public void print(){for(int i=0;i<curIndex;i++){System.out.print(SqList[i]+"\t");}System.out.println();}}

  Main函數測試

package list;public class SequenceListMain {public static void main(String[] args) {SequenceList sqList = new SequenceList();sqList.initList();sqList.insertList(1);sqList.insertList(2);sqList.insertList(3);sqList.insertList(4);sqList.insertList(5);sqList.insertList(6);sqList.delete(5);sqList.delete(9);sqList.insertList(1);sqList.print();sqList.delete(1);sqList.print();System.out.println("第2個元素是:"+sqList.getElement(1));System.out.println("第4個元素是:"+sqList.getElement(4));}}

  

java實現順序鏈表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.