您的位置:首页 > 编程语言 > Java开发

Java顺序表的实现

2017-12-30 20:16 197 查看
线性表是由n(n>=0)个元素构成的有限序列,通常表示为a0,a1,a2, ...,an-1,它是最简单的数据结构。而顺序表就是顺序存储的线性表,它是用一组地址连续的存储单元依次存放各个数据元素的存储结构。
顺序表的主要操作有清空、判断是否为空、求当前长度、获取某个位置元素、插入、删除、查找元素位置等。其中几项很简单,只有插入、删除可能要思考一下,但也是容易解决的。
代码如下:
public class SqlList{

public Object[] listElement;
public int currentLength;

public SqlList(int maxSize)
{
listElement=new Object[maxSize];
currentLength=0;
}

//清空
public void clear()
{
currentLength=0;
}
//是否为空
public boolean isEmpty()
{
return currentLength==0;
}
//当前长度
public int length()
{
return currentLength;
}

//插入
public void insert(int i,Object x) throws Exception
{
if(currentLength==listElement.length)
new Exception("顺序表已满!");
if(i<0 || i>currentLength)
{
throw new Exception("插入位置不合法!");
}
for(int j=currentLength;j>i;j--)
listElement[j]=listElement[j-1];
listElement[i]=x;
currentLength++;
}
//删除
public void remove(int i) throws Exception
{
if(i<0 || i>=currentLength)
throw new Exception("删除位置不合法");
for(int j=i;j<currentLength-1;j++)
{
listElement[j]=listElement[j+1];
}
currentLength--;
}

//获取某个位置元素
public Object get(int i) throws Exception
{
if(i<0 || i>=currentLength)
{
throw new Exception("第" + i
4000
+ "不存在");
}
return listElement[i];
}
//查找元素所在位置下标
public int indexOf(Object x)
{
for(int i=0;i<currentLength;i++)
{
if(listElement[i].equals(x))
return i;
}
return -1;
}

//打印输出
public void display()
{
for(int i=0;i<currentLength;i++)
{
System.out.print(listElement[i]+" ");
}
System.out.println();
}

public static void main(String[] args) throws Exception
{
SqlList sqlList=new SqlList(30);
sqlList.insert(0,5);
sqlList.insert(1,9);
sqlList.insert(2,8);
System.out.print("所有元素:");
sqlList.display();
System.out.println("9的下标是:"+sqlList.indexOf(9));
sqlList.remove(2);
System.out.print("删除下标为2的元素后: ");
for(int i=0; i<sqlList.length(); i++)
System.out.print(sqlList.get(i)+" ");
System.out.println();
}
}可以看到顺序表内部是采用一个一维数组来存储数据元素,并没有什么复杂的东西,多看看就Ok了。若有问题,敬请指正!(凡星逝水2017)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息