顺序表
- 顺序表其实就是一个写到类中的数组。写到类中就可以面向对象了。实现增删改查。
- 顺序表特点
- 物理上和逻辑上都是连续的
- 插入和删除元素,必须移动元素。(时间复杂度:O(N))
- 扩容也是问题
- 可以实现随机读取(查找时间复杂度:O(1))
- 顺序表的代码目录
public class SeqList {
// 打印顺序表
public void display() { }
// 在 pos 位置新增元素
public void add(int pos, int data) { }
// 判定是否包含某个元素
public boolean contains(int toFind) { return true; }
// 查找某个元素对应的位置
public int search(int toFind) { return -1; }
// 获取 pos 位置的元素
public int getPos(int pos) { return -1; }
// 给 pos 位置的元素设为 value
public void setPos(int pos, int value) { }
//删除第一次出现的关键字key
public void remove(int toRemove) { }
// 获取顺序表长度
public int size() { return 0; }
// 清空顺序表
public void clear() { }
}
- 顺序表类的具体代码实现:
public class MyArrayList {
public int[] elem;
public int usedSize; //当前数组有效数组的个数
public MyArrayList() {
this.elem = new int[10];
}
// 打印顺序表
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
// 获取顺序表的有效长度
public int size() {
return this.usedSize;
}
//判断顺序表是否满了
public boolean isFull() {
if (this.usedSize == this.elem.length) {
return true;
}
return false;
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
//1.判断pos是否合法:pos<0 || pos > usedSize(前面没有元素)就不能放
if (pos < 0 || pos > usedSize) {
System.out.println("pos 位置不合法!");
return;
}
//2.判断满不满,如果满了,需要扩容。(Java没有扩容失败的问题)
if (this.isFull()) {
this.elem = Arrays.copyOf(this.elem, 2*this.elem.length);
}
//3.移动元素,给pos位置腾位置
for (int i = this.usedSize-1; i >= pos; i++) {
this.elem[i+1] = this.elem[i];
}
//4.插入,usedSize++
this.elem[pos] = data;
usedSize++;
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (this.elem[i] == toFind) {
return true;
}
}
return false;
}
// 查找某个元素对应的位置,找不到返回-1
public int search(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (this.elem[i] == toFind) {
return i;
}
}
return -1;
}
public boolean isEmpty() {
return this.usedSize == 0;
}
// 获取 pos 位置的元素
public int getPos(int pos) {
//1.判断pos是否合法
if (pos < 0 || pos >= this.usedSize) {
System.out.println("pos 位置不合法!");
return -1; //业务上的处理这里暂时不考虑,后期这里可以抛出异常
}
//2.判断顺序表是否为空
if (isEmpty()) {
return -1;
}
return this.elem[pos];
}
// 给 pos 位置的元素 设为/更新为 value
public void setPos(int pos, int value) {
if (pos < 0 || pos >= this.usedSize) {
System.out.println("pos位置不合法");
return;
}
if (isEmpty()) {
System.out.println("顺序表为空!");
return;
}
this.elem[pos] = value;
}
//删除第一次出现的关键字key
public void remove(int toRemove) {
//1. 判断顺序表是否为空
if (isEmpty()) {
System.out.println("顺序表为空");
return;
}
//2. 查找要删除的数字toRemove的下标index
int index = this.search(toRemove);
if (index == -1) {
System.out.println("没有要找的数字!");
return;
}
//3. 从index的下一位开始,逐步往前覆盖。useSize-1;
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize -= 1;
}
// 清空顺序表
public void clear() {
//如果是简单类型的顺序表(只是存的数字、字符等)
this.usedSize = 0;
//但如果是引用类型的顺序表(存的是地址),必须将每个元素置为null
}
}