线性表的顺序存储
顺序表的定义:
所谓顺序表,就是顺序存储的线性表。顺序表是用一组地址连续的存储单元依次存放线性表中各个数据元素的存储结构。
顺序表的特点:
1)在线性表中逻辑上相邻的数据元素,在屋里存储位置上也是相邻的。
2)存储的密度高,但需要预先分配足够应用的存储空间,这可能将会造成存储空间的浪费。
3)便于随机存取。
4)不便于插入和删除操作,这是因为在顺序表上插入和删除操作会引起大量数据元素的移动。
顺序表的一些操作如下:
接口部分代码展示:
package 顺序表;
public interface Ilist {
public void clear();
public boolean isEmpty();
public int length();
public Object get(int i) throws Exception;
public void insert (int i,Object x) throws Exception;
public void remove(int i) throws Exception ;
public int indexOf(Object x);
public void display();
}
实现类展示如下:
package 顺序表;
import java.util.Scanner;
public class SqList implements Ilist{
private Object[] listElem;//线性表存储空间
private int curLen ;//线性表当前长度
//构造一个存储空间容量为maxSize的线性表
//构造函数
public SqList(int maxSize) {
listElem=new Object[maxSize];
curLen=0;
}
@Override//将一个已经存在的线性表成为空表
public void clear() {
// TODO Auto-generated method stub
curLen=0;
}
@Override//判断线性表中的数据元素的个数是否为0,如果为0则返回true;如果不是则返回false
public boolean isEmpty() {
// TODO Auto-generated method stub
return curLen==0;
}
@Override//求线性表中的数据元素的个数并返回其值
public int length() {
// TODO Auto-generated method stub
return curLen;
}
@Override //读取到线性表中的第i个数据元素,并由函数返回其值,其中i为0<=i<=length()-1,若不存在i值则抛出异常
public Object get(int i) throws Exception {
// TODO Auto-generated method stub
return listElem[i];
}
@Override//在线性表的第i个数据元素之前插入一个值为x的数据元素
public void insert(int i, Object x) throws Exception {
// TODO Auto-generated method stub
if(i==listElem.length) {
throw new Exception("数组满了");
}
if(i<0||i>curLen) {
throw new Exception("插入的数据位置不存在");
}
for(int j=curLen;i<curLen;j--) {
listElem[j]=listElem[j--];
}
listElem[i]=x;
curLen++;
}
@Override//删除并返回线性表的第i个数据元素
public void remove(int i) throws Exception {
// TODO Auto-generated method stub
if(i>curLen-1||i<0) {
throw new Exception("插入错误");
}
for(int j=i;j<curLen-1;j++) {
listElem[j]=listElem[j+1];
}
curLen--;
}
@Override//返回线性表首次出现指定的数据元素的位序号,若线性表中不包含此数据元素,则返回-1
public int indexOf(Object x) {
// TODO Auto-generated method stub
int j=0;
while(j<curLen&&!listElem[j].equals(x)) {
j++;
}
if(j<curLen)
return j;
else
return -1;
}
@Override
public void display() {
// TODO Auto-generated method stub
for(int i=0;i<curLen;i++) {
System.out.print(listElem[i]);
}
}
}
测试类如下:`
package 顺序表;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception {
SqList sq=new SqList(10);
sq.insert(0, "1");
sq.insert(1, "2");
sq.remove(0);
sq.display();
System.out.println(sq.indexOf("2"));
}
}
来源:CSDN
作者:LustTiger
链接:https://blog.csdn.net/lusttiger/article/details/104397695