想看看java版的数据结构,了解一下树的一些操作,写了个顺序表熟悉一下
1 package com.sqlist; 2 3 /** 4 * @author xiangfei 5 * 定义一个顺序表 6 * 7 */ 8 public class SqlList { 9 final int deflen = 10; 10 int maxlen; 11 int curlen; 12 Object elements[]; 13 14 /** 15 * 默认构造方法 16 */ 17 public SqlList(){ 18 maxlen = deflen; 19 curlen = 0; 20 elements = new Object[maxlen]; 21 } 22 /** 23 * 根据一个数据和最大长度初始化一个数据表 24 * @param array 25 * @param maxlen 26 */ 27 public SqlList(Object array[], int maxlen){ 28 this.maxlen = array.length > maxlen ? array.length : maxlen; 29 curlen = array.length; 30 elements = new Object[this.maxlen]; 31 32 //copy 33 for(int i = 0; i < maxlen; i++){ 34 elements[i] = array[i]; 35 } 36 } 37 /** 38 * @param sqlList 39 * 拷贝构造方法 40 */ 41 public SqlList(SqlList sqlList){ 42 this.maxlen = sqlList.maxlen; 43 this.curlen = sqlList.curlen; 44 //这里用深度拷贝 45 elements = new Object[this.maxlen]; 46 //copy 47 for(int i = 0; i < this.maxlen; i++){ 48 elements[i] = sqlList.elements[i]; 49 } 50 } 51 /** 52 * 向指定位置position插入元素element 53 * @param element 54 * @param position 55 * @return 56 */ 57 public boolean insertElement(Object element, int position){ 58 if(position < 0 || position >= maxlen) 59 return false; 60 else{ 61 int i = curlen - 1; 62 while(i > position){ 63 elements[i] = elements[i - 1]; 64 } 65 elements[position] = element; 66 return true; 67 } 68 } 69 /** 70 * 删除指定位置的元素 71 * @param position 72 * @return 73 */ 74 public Object deleteElement(int position){ 75 if(position < 0 || position >= curlen) 76 return null; 77 else{ 78 Object elementDel = elements[position]; 79 int i = position; 80 while(i < curlen){ 81 elements[i] = elements[i + 1]; 82 } 83 return elementDel; 84 } 85 } 86 /** 87 * 打印所有的元素 88 */ 89 public void showSqlList(){ 90 for(int i = 0; i < curlen; i++) 91 { 92 System.out.print(elements[i].toString() + " "); 93 } 94 } 95 }
测试类(这里只测了一个构造方法,其他方法也写的很粗糙)
1 package com.sqlist; 2 3 /** 4 * 测试顺序表 5 * @author xiangfei 6 * 7 */ 8 public class SqlListTest { 9 public static void main(String args[]){ 10 Integer array_int[] = new Integer[]{1, 2, 3}; 11 SqlList sqlList = new SqlList(array_int, 3); 12 13 sqlList.showSqlList(); 14 } 15 }
时间: 2024-11-20 15:48:57