线性表
线性表(linear list)是n个具有相同特性的数据元素的有限序列。 线性表是一种在实际中广泛使用的数据结构,常见的线性表:顺序表、链表、栈、队列、字符串…
线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的,线性表在物理上存储时,通常以数组和链式结构的形式存储。
顺序表
定义
用一段物理地址连续的存储单元依次存储数据元素的线性结构。
一般采用数组存储,在数组中进行数据的增删查改
静态顺序表
使用定长数组存储。
适用于知道存多少数据的场景
动态顺序表
使用动态开辟的数组存储
根据需要分配空间大小
实现动态顺序表
public class MyArrayList {
public int[] elem;
public int usedSize;
public MyArrayList(){
this.elem = new int[10];
this.usedSize = 0;
}
public MyArrayList(int capcity){
this.elem = new int[capcity];
this.usedSize = 0;
}
//扩容
public void resize(){
this.elem = Arrays.copyOf(this.elem,this.elem.length*2);
}
//在pos位置插入元素
public void add(int pos,int data){
if(pos < 0 || pos > usedSize){
System.out.println("pos位置不合适");
return;
}
if(pos == this.elem.length){
resize();
}
for (int i = this.usedSize-1; i >= pos ; i--) {
this.elem[i+1] = this.elem[i];
}
this.elem[pos] = data;
usedSize++;
}
//打印顺序表
public void display(){
for (int i = 0; i < this.usedSize ; i++) {
System.out.println(this.elem[i]+" ");
}
}
//判断是否包含某个元素
public boolean contains(int toFind){
for (int i = 0; i < this.usedSize; i++) {
if(elem[i] == toFind){
return true;
}
}
return false;
}
//查找某个元素的对应位置
public int search(int toFind){
for (int i = 0; i < this.usedSize; i++) {
if(elem[i] == toFind){
return i;
}
}
return -1;
}
//获取pos位置的元素
public int getPos(int pos){
if(pos < 0 || pos > this.usedSize){
System.out.println("pos位置不合法");
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 ;
}
this.elem[pos] = value;
}
//获取顺序表的长度
public int size(){
return this.usedSize;
}
//删除第一次出现的关键字key
public boolean remove(int toRemove){
//获取删除元素的下标
int index = search(toRemove);
if(index == -1){
System.out.println("没有这个数字");
return false;
}
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
usedSize--;
return true;
}
//删除在顺序表中的所有Key
public void removeAll(int toRemove){
for (int i = 0; i < usedSize; i++) {
if(elem[i] == toRemove){
for (int j = i; j < usedSize-1; j++) {
elem[j] = elem[j+1];
}
usedSize--;
}
}
}
//判断顺序表是否已满
public boolean isFull(){
if(this.usedSize == this.elem.length){
return true;
}
return false;
}
//清空顺序表
public void clean(){
this.usedSize = 0;
}
}