Java实现线性表的顺序存储
本文实例为大家分享了Java实现线性表的顺序存储,供大家参考,具体内容如下
顺序表:用一组地址连续的存储单元依次存储各个元素,使得在逻辑结构上相邻的数据元素存储在相邻的物理存储单元中的线性表
packagealgorithm.datastructure.seqlist;
/*顺序表
*
*用一组地址连续的存储单元依次存储各个元素,使得在逻辑结构上相邻的数据元素存储在相邻的物理存储单元中的线性表
*
*/
publicclassSeqList{
privateintlength;//顺序表长度
privateint[]list;//数组,连续的存储空间
//初始化,构造一个空的线性表
publicSeqList(intlistLength){
list=newint[listLength];
}
//销毁表
publicvoiddestroyList(){
list=null;
this.length=0;
}
//将线性表置为空表
publicvoidclearList(){
for(inti=0;i=getLength()){
try{
thrownewException("线性表下标越界");
}catch(Exceptione){
e.printStackTrace();
}
}
returnlist[i];
}
//返回某元素(第一个)的前驱
publicIntegerpriorElem(intelement){
for(inti=0;i=list.length){//扩容
inttempList[]=newint[list.length*2];
for(inti=0;i=list.length){
try{
thrownewException("下标错误");
}catch(Exceptione){
e.printStackTrace();
}
}
if(index==getLength()){
returninsertTailElement(element);
}
for(inti=0;i=index;j--){
list[j+1]=list[j];
}
list[index]=element;
length++;
}
}
returntrue;
}
//尾部插入元素
publicBooleaninsertTailElement(intelement){
ensureCapacity(length+1);
list[++length]=element;
returntrue;
}
//删除尾部元素
publicintdeleteTailElement(){
if(getLength()==0){
try{
thrownewException("下标错误");
}catch(Exceptione){
e.printStackTrace();
}
}
inttailElement=list[getLength()-1];
list[getLength()-1]=0;
length--;
returntailElement;
}
//删除元素
publicintdeleteElement(intindex){
if(index<0||index>=list.length){
try{
thrownewException("下标错误");
}catch(Exceptione){
e.printStackTrace();
}
}
if(index==getLength()){
returndeleteTailElement();
}
for(inti=0;i
以上就是用Java简单实现的顺序表,在Java中,如果要实现功能更复杂,性能更高的顺序表,可参考ArrayList源码。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。