顺序表
概念:
顺序表是一段物理地址连续的存储单元一次存储数据元素的线性结构,一般来说用数组存储。在数组上完成数据的增删改查。
静态顺序表适用于确定知道需要存多少数据的场景,顺序表底层是一个数据,但是顺序表本事是一种数据结构。
特性
- 能知道放了几个元素
- 不能跳着放
用图形表示如下图
顺序表的增删改查操作
首先构造一个顺序表
public class MyArrayList {
public int[] elem;//数组
public int usedSize;//有效的数据个数
public static final int capacity = 10;//初始容量
public MyArrayList() {
this.elem = new int[capacity];
this.usedSize = 0;
}
增加操作
// 在 pos 位置新增元素
public void add(int pos, int data) {
//1、判断 pos 位置是否合法
//2、挪数据 当 i< pos 完成
//3、this.elem[pos] = data;
if (isFull()){
this.elem = Arrays.copyOf(this.elem,2 * this.elem.length);
}
if (pos > usedSize || pos < 0){
System.out.println("pos 值不合法");
return;
}
for (int i = usedSize - 1; i >= pos; i--) {
this.elem[i + 1] = this.elem[i];
}
this.elem[pos] = data;
this.usedSize++;
}
private boolean isFull(){
if (this.usedSize == this.elem.length){
return true;
}
return false;
}
打印操作
//打印顺序表
public void display() {
for (int i = 0; i < usedSize; i++) {
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
运行效果
public class TestDemo {
public static void main(String[] args) {
MyArrayList myArrayList1 = new MyArrayList();
for (int i = 0; i < 10; i++) {
myArrayList1.add(i,i);
}
myArrayList1.display();
}
}
现在内存容量已经满了,我们设置的初始内存是 10,现在继续添加元素
添加成功
查找
// 判定是否包含某个元素
public boolean contains(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (toFind == elem[i]){
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int search(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (toFind == elem[i]) {
return i;
}
}
return -1;
}
3 是否存在
查找值为 3 的位置 也是 3
获取 POS 位置的元素
//判断是否为空
private boolean isEmpty(){
return this.usedSize == 0;
}
//判断 pos 值是否合法
private void checkPos(int pos){
if (pos >= usedSize || pos < 0){
throw new RuntimeException("pos 值不合法!");
}
}
// 获取 pos 位置的元素
public int getPos(int pos) {
//1、顺序表是否为空
//return pos 位置
if (isEmpty()){
//return -1;
throw new RuntimeException("顺序表为空!");
}
//2、判断 pos 合法性
checkPos(pos);
return elem[pos];
}
查找位置为 3 的元素
查找 pos 为 20(此 pos 不合法)的值
checkPos() 方法可以适用于所有需要查看 pos 是否合法的位置
删除数字
删除第一次出现的关键字 key
public void remove(int toRemove) {
int i = search(toRemove);
if (i == -1){
System.out.println("没有需要删除的数字!");
return;
}
while (i < this.usedSize - 1) {
elem[i] = elem[i+1];
i++;
}
this.usedSize--;
}
运行效果
获取顺序表长度
// 获取顺序表长度
public int size() {
return this.usedSize;
}
运行效果
清空顺序表
public void clean(){
this.usedSize = 0;
}
展示效果