顺序表
概念
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
顺序表一般可以分为:
- 静态顺序表:使用定长数组存储。
- 动态顺序表:使用动态开辟的数组存储。
静态顺序表适用于确定知道需要存多少数据的场景。
静态顺序表的定长数组导致,空间开多了浪费,空间开少了不够用。相比之下动态顺序表更灵活,根据需要动态的分配空间大小。
测试文件:
public class TestDemo1 {
public static void main(String[] args) {
MyArrayList myArrayList1 = new MyArrayList();
myArrayList1.add(0,12);
myArrayList1.add(1,23);
myArrayList1.add(2,34);
myArrayList1.add(3,45);
myArrayList1.add(4,57);
myArrayList1.display();
System.out.println(myArrayList1.contains(100));
System.out.println(myArrayList1.search(57));
System.out.println(myArrayList1.size());
myArrayList1.setPos(4,66);
myArrayList1.display();
myArrayList1.clear();
System.out.println("数据已清空");
myArrayList1.display();
}
}
顺序表的功能实现文件
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;
}
private boolean isFull(){//判断数组存储元素是否满了
if (this.usedSize == this.elem.length){
return true;
}
return false;
}
private boolean isEmpty(){
return this.usedSize == 0;
}
public void display(){//打印顺序表
for(int i = 0;i < this.usedSize;i++){
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
public void add(int pos,int data){//在pos位置新增元素
/*分为3步:
* 1:判断pos位置是否合法,以及该数组是不是满了。(pos不能是负数,并且pos应该<=usedSize)
* 2:挪数据。(首先令i = usedSize-1,然后[i+1]=[i]搬,当i<pos的时候表示挪完数据了)
* 3:把数据放到指定的位置(this.elem[pos] = data;)*/
if(pos < 0 || pos > this.usedSize){//判断pos位置是否合法
return;
}
if (isFull()){//考虑扩容的问题
this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);//这就是二倍扩容
}
//到这一步开始挪数据了
for (int i = this.usedSize-1; i>=pos;i--){
this.elem[i+1] = this.elem[i];
}
//说明数据挪完了
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;
}
public int getPos(int pos){//获取pos位置的元素
/*分为3步:
* 1:判断该顺序表是否为空
* 2:判断pos位置的合法性
* 3:再来返回pos位置的元素*/
//1.顺序表是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空!");//手动抛出一个异常
}
//2.pos合法性
if(pos < 0||pos >=this.usedSize){
throw new RuntimeException("pos位置不合法!");
}
//3.return pos位置的数据就OK了
return this.elem[pos];
}
public void setPos(int pos,int value) {//给pos位置的元素设为value
if(pos < 0||pos >=this.usedSize){//判断pos位置是否合法
throw new RuntimeException("pos位置不合法!");
}
this.elem[pos] = value;
}
public void remove(int toRemove){//删除第一次出现的关键字key
int index = search(toRemove);
if(index == -1){
System.out.println("没有需要删除的数字!");
return;
}
for(int i = index;i < this.usedSize-1;i++){
this.elem[i] = this.elem[i+1];
}
this.usedSize--;
}
public int size(){//获取顺序表长度
return this.usedSize;
}
public void clear(){//清空顺序表
this.usedSize = 0;
}
}