顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删改查。
顺序表的结构
向数组中插入一个元素,usedSize就会加1.
顺序表一般分为:
静态顺序表:使用定长数组存储
动态顺序表:使用动态开辟的数组存储
静态顺序表适用于确定知道需要存多少数据的场景.
静态顺序表的定长数组导致N定大了,空间开多了浪费,开少了不够够。
相比之下动态顺序表更灵活, 根据需要动态的分配空间大小.
此处实现一个动态顺序表。
public class MyArrayList {
public int[] elem;
public int usedSize;//有效数据个数
public static final int intCapacity = 10;//初始容量
public MyArrayList() {
this.elem = new int[intCapacity];
this.usedSize = 0;
}
// 打印顺序表
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
private boolean ifFull() {
if(this.usedSize == this.elem.length) {
return true;
}
return false;
}
private void checkPos(int pos) {
if(pos < 0 || pos > this.usedSize) {
throw new RuntimeException("pos位置不合法");
}
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
if(ifFull()){
//扩容
this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
//return;
}
//1、判断pos位置是否合法
checkPos(pos);
//2、挪数据,从i=usedSize-1位置开始,[i+1] = [i]。当i<pos停止
for (int i = usedSize -1; i >= pos; i--) {
this.elem[i+1] = this.elem[i];
}
//3、this.elem[pos]=data;
this.elem[pos] = data;
this.usedSize++;
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind){
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int search(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind){
return i;
}
}
return -1;
}
private boolean isEmpty() {
return this.usedSize == 0;
}
// 获取 pos 位置的元素
public int getPos(int pos) {
//1、顺序表是否为空
if(isEmpty()) {
//return -1;
throw new RuntimeException("顺序表为空");//手动抛出异常
}
//2、pos是否合法
if(pos < 0 || pos >= this.usedSize) {
throw new RuntimeException("pos位置不合法!");
}
//3、return pos位置
return this.elem[pos];
}
//删除第一次出现的关键字key
public void remove(int toRemove) {
//1、找数字,并得到他的下标
int index = search(toRemove);
if(index == -1){
System.out.println("没有需要删除的数据!");
return;
}
//2、挪数据,让后面的值覆盖前面的值
for (int i = index; i < this.usedSize -1; i++) {
this.elem[i] = this.elem[i+1];
}
//3、usedSize--
this.usedSize--;
}
// 获取顺序表长度
public int size() {
return this.usedSize;
}
// 清空顺序表
public void clear(){
this.usedSize = 0;
}
//更新pos位置元素
public void setPos(int pos,int value) {
if(pos < 0 || pos >= this.usedSize) {
throw new RuntimeException("pos位置不合法");
}
this.elem[pos] = value;
}
}