线性表java实现之顺序存储源码
源码:
class SequenceList<T>{
private int size=0;//表大小
private int max_length;//表长
private final int default_length = 20;//默认长度
private Object[] o;
//初始化
public SequenceList(){
max_length = default_length;
o = new Object[max_length];
}
public SequenceList(int init_length,T data){
max_length = init_length;
o=new Object[max_length];
o[0]=data;
size++;
}
//返回长度
public int getLength(){
return max_length;
}
//返回指定索引处值
/**
* @param location
* @return
*/
@SuppressWarnings("unchecked")
public T getValue(int location){
return (T) o[location];
}
//返回指定值的位置
public int getLocate(T data){
int tag=size-1;
while(tag>0){
if(o[tag].equals(data)){
break;
}
tag--;
}
return tag;
}
//插入数据
public void insert(T data,int location){
if(size > max_length-1){
throw new IndexOutOfBoundsException("超过线性表最大长度");
}else{
int flag = size;
while(flag>location){
o[flag] = o[flag-1];
flag--;
}
o[flag] = data;
size++;
}
}
public void add(T data){
insert(data, size);
}
//删除数据
public T delete(int location){
@SuppressWarnings("unchecked")
T old_value = (T) o[location];
if(location<0 || location > size-1){
throw new IndexOutOfBoundsException("不再线性表范围");
}else{
while(location<size-1){
o[location] = o[location+1];
location++;
}
o[--size] = null;
}
return old_value;
}
//判断是否空表
public boolean isEmpty(){
if(size>0)
return false;
else
return true;
}
//清空表
public void clear(){
while(--size>=0){
o[size] = null;
}
}
@Override
public String toString() {
if(size <0 )
return "[]";
else{
StringBuffer sb = new StringBuffer("[");
int flag = 0;
while(flag < size){
sb.append(o[flag].toString()+",");
flag++;
}
return sb.delete(sb.length()-1, sb.length()).toString()+"]";
}
}
@Override
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(obj == this){
return true;
}
if(obj instanceof SequenceList){
@SuppressWarnings("unchecked")
SequenceList<T> s = (SequenceList<T>) obj;
if(s.size == size){
int flag=0;
while(o[flag] == s.o[flag]){
flag++;
}
if(flag == size-1){
return true;
}
}
}
return false;
}
}