- package org.danlley.util;
- /**
- * @version 1.0
- * @since 2006 年 9 月 17 日 14 : 42 pm
- * @author weixm
- * 說明:這是一個用數組實現的順序表,實現了基本的增、刪、查操作。
- */
- public class SequenList {
- public int length=10;//初始化順序表大小爲10
- private int cur_index;//當前插入位置
- private Object[] seqList;//順序表數據存放處
- /**
- * @author weixm
- * 說明:構造函數,用來初始化順序表。此處用私有方法來對數據進行初始化。
- */
- public SequenList(){
- initList();
- }
- /**
- * @author weixm
- * 初始化順序表
- */
- private void initList(){
- this.seqList=new Object[length];
- }
- /**
- * @author weixm
- * @param obj
- * 說明:此方法用來在順序表中最後位置添加新數據,當數據添加位置超過了數組允許大小時,
- * 重新分配內存空間。並且,每加一條數據,List的當前插入位置自增“1”。
- */
- public void add(Object obj){
- if(length>0){
- if(cur_index<(length-1)){
- seqList[cur_index]=obj;
- cur_index++;
- }else{
- resizeList(seqList);
- seqList[cur_index]=obj;
- cur_index++;
- }
- }else{
- System.err.print("The sequences are not initialed properly ! ");
- }
- }
- /**
- * @author weixm
- * @param index
- * @param obj
- * 說明:此方法用來在數組的任意位置添加一個新數據。如果任意插入的數據位置剛好是最後一個元素
- * 則直接調用 add(Object obj) 方法,如果添加的數據超出了原始數據的邊界值,則List
- * 會自動對空間進行擴充。因此,允許添加數據的當前位置超出數據邊界。但是每次插入的數據
- * 索引大小不能超過 length*3/2+1 ,否則,系統會拋出數組越界異常。
- */
- public void add(int index,Object obj){
- if(index==cur_index+1){
- add(obj);
- }else{
- int old_len=length;
- if(index>length-1){
- resizeList(seqList);
- }
- System.arraycopy(seqList,index,seqList,index+1,old_len-index);
- seqList[index]=obj;
- cur_index=index;
- }
- }
- /**
- * @author weixm
- * @param obj
- * @return
- * 說明:此方法用於進行元素查找,如果要查找的元素在數據中存在,則返回數據所在位置,如果
- * 元素在數據中沒有找到,則直接返回 -1 。
- */
- public int findElement(Object obj){
- int find_index=-1;
- for(int i=0;i
- if(obj.equals(seqList[i])){
- find_index=i;
- }
- }
- return find_index;
- }
- /**
- * @author weixm
- * @param index
- * @return
- * 說明:此方法用來得到某個確定位置的元素。
- */
- public Object get(int index){
- return seqList[index];
- }
- /**
- * @author weixm
- * @param seqList_low
- * 說明:重新劃分並擴充數據所佔內存空間,具體擴充方式爲: length*3/2+1 。
- */
- public void resizeList(Object[] seqList_low){
- int resize=length*3/2+1;
- Object[] seqList_upp=new Object[resize];
- System.arraycopy(seqList_low,0,seqList_upp,0,length);
- seqList=seqList_upp;
- length=resize;
- }
- /**
- * @author weixm
- * @param args
- * 說明:測試用例
- */
- // public static void main(String[] args)throws Exception{
- // try{
- // SequenList list=new SequenList();
- // for(int i=0;i<100;i++){
- // list.add(""+i);
- // //System.out.println(" "+list.get(i));
- // }
- // list.add(133," TEST ");
- // System.out.println(""+list.findElement(""+98));
- // System.out.println(""+list.findElement(" TEST "));
- // System.out.println(""+list.findElement("TEST"));
- // for(int i=0;i
- // System.out.println(" "+list.get(i));
- // }
- // System.out.println("++++++++++++ "+list.length);
- // }catch(Exception e){
- // throw new Exception(e);
- // }
- // }
- }
用Java實現的順序鏈表
java 代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.