想看看java版的数据结构,了解一下树的一些操作,写了个顺序表熟悉一下
package com.sqlist; /**
* @author xiangfei
* 定义一个顺序表
*
*/
public class SqlList {
final int deflen = 10;
int maxlen;
int curlen;
Object elements[]; /**
* 默认构造方法
*/
public SqlList(){
maxlen = deflen;
curlen = 0;
elements = new Object[maxlen];
}
/**
* 根据一个数据和最大长度初始化一个数据表
* @param array
* @param maxlen
*/
public SqlList(Object array[], int maxlen){
this.maxlen = array.length > maxlen ? array.length : maxlen;
curlen = array.length;
elements = new Object[this.maxlen]; //copy
for(int i = 0; i < maxlen; i++){
elements[i] = array[i];
}
}
/**
* @param sqlList
* 拷贝构造方法
*/
public SqlList(SqlList sqlList){
this.maxlen = sqlList.maxlen;
this.curlen = sqlList.curlen;
//这里用深度拷贝
elements = new Object[this.maxlen];
//copy
for(int i = 0; i < this.maxlen; i++){
elements[i] = sqlList.elements[i];
}
}
/**
* 向指定位置position插入元素element
* @param element
* @param position
* @return
*/
public boolean insertElement(Object element, int position){
if(position < 0 || position >= maxlen)
return false;
else{
int i = curlen - 1;
while(i > position){
elements[i] = elements[i - 1];
}
elements[position] = element;
return true;
}
}
/**
* 删除指定位置的元素
* @param position
* @return
*/
public Object deleteElement(int position){
if(position < 0 || position >= curlen)
return null;
else{
Object elementDel = elements[position];
int i = position;
while(i < curlen){
elements[i] = elements[i + 1];
}
return elementDel;
}
}
/**
* 打印所有的元素
*/
public void showSqlList(){
for(int i = 0; i < curlen; i++)
{
System.out.print(elements[i].toString() + " ");
}
}
}
测试类(这里只测了一个构造方法,其他方法也写的很粗糙)
package com.sqlist; /**
* 测试顺序表
* @author xiangfei
*
*/
public class SqlListTest {
public static void main(String args[]){
Integer array_int[] = new Integer[]{1, 2, 3};
SqlList sqlList = new SqlList(array_int, 3); sqlList.showSqlList();
}
}