java线性表源代码_线性表java实现之顺序存储源码
源碼:
class SequenceList{
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
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 s = (SequenceList) obj;
if(s.size == size){
int flag=0;
while(o[flag] == s.o[flag]){
flag++;
}
if(flag == size-1){
return true;
}
}
}
return false;
}
}
總結
以上是生活随笔為你收集整理的java线性表源代码_线性表java实现之顺序存储源码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 优盘里面的文件怎么不能删除不了怎么办 优
- 下一篇: 怎么输出链表长度C语言,下面程序输出结果