线性表的定义:
由0个或多个数据组成的有限序列(a1,a2 .....an)
数据类型:
是指一组性质相同的值得集合及定义在此集合上的一些操作的总称(整型,浮点型,字符型等就是数据类型)
线性表有两种物理存储结构(在内存中找个初始地址):
顺序存储结构和链式存储结构
线性表的顺序存储结构
特点:
顺序存储结构指的是用一段连续的存储单元依次来存储线性表的数据元素。
优缺点:
优点:查询很快 时间复杂度为o(1)
缺点:插入和删除效率慢 (需要移动元素位置)时间复杂度为0(n)
线性表的操作
建表(初始化)、求表长、查找、插入、删除
/* 顺序线性表的操作*/
public class OrderTableOp {
//默认的顺序表的最大长度
final int defaultSize =10;
//最大长度
int maxSize;
//当前线性表的长度
int currTableLength;
// 存放数据的对象数组
Object[]listArray;
//默认大小
public OrderTableOp() {
init(defaultSize);
}
//给定大小
public OrderTableOp(int size) {
init(size);
}
//顺序表的初始化方法
private void init(int size) {
maxSize = size;
this.currTableLength =0;
listArray =new Object[size];
}
public Objectget(int index)throws Exception {
if(isEmpty()){
throw new Exception("该表为空");
}
if(index<0||index>currTableLength){
throw new Exception("请检查index");
}
return listArray[index];
}
//一直加表的末尾
public void insert(Object object)throws Exception {
if(currTableLength ==maxSize){
throw new Exception("当前线性表已满");
}
listArray[size()] = object;
currTableLength++;
}
public void insert(int index, Object obj)throws Exception {
if(currTableLength ==maxSize){
throw new Exception("当前线性表已满");
}
//插入编号是否合法
if(index<0 || index>currTableLength){
throw new Exception("请检查index");
}
// 所有下标>index的向后移动一位
/**
* 最后一位先移动(后移一位),所以用currTableLength-1
* 并把 currTableLength-1 赋值给 j
* 判断(只要j>= index 的 全部向后移动一位 j+1)
*/
for (int j=currTableLength-1;j>=index;j--){
listArray[j+1]=listArray[j];
}
listArray[index] = obj;
currTableLength++;
}
public void delete(int index)throws Exception {
if(index<0||index>currTableLength){
throw new Exception("请检查index");
}
for(int j = index;j <=currTableLength-1;j++){
listArray[j-1]=listArray[j];
}
currTableLength--;
}
public int size() {
return currTableLength;
}
public boolean isEmpty(){
if(currTableLength ==0){
return true;
}
return false;
}
}
网友评论