顺序表:基于数组实现,物理内存连续,逻辑连续
插入和删除时间复杂度为O(n)
查找时间复杂度为 O(1)
MyArrayList类
import java.util.Arrays;
/**
* @className MyArrayList
* @Description TODO
* @Author zhangqianqian
* @Date 2019/10/27 11:13
* @Version 1.0
**/
public class MyArrayList {
public int usedSize;
public int[] elem;
public final int CAPACITY=4;//定义顺序表长度
//构造方法初始化顺序表
public MyArrayList() {
this.usedSize = 0;
this.elem = new int[CAPACITY];
}
//判断顺序表是否满
private boolean isFull(){
return this.usedSize==this.elem.length;
}
//在顺序表pos位置添加data
public void add(int pos,int data){
if(isFull()){
this.elem=Arrays.copyOf(this.elem,CAPACITY*2);
}
if(pos>this.usedSize||pos<0){
throw new IndexOutOfBoundsException("位置不合法");
//System.out.println("插入不合法");
//return;
}
else{
for (int i = this.usedSize; i >pos ; i--) {
this.elem[i]=this.elem[i-1];
}
this.elem[pos]=data;
this.usedSize++;
}
}
//判断顺序表是否为空
public boolean isEmpty(){
return this.usedSize==0;
}
//在顺序表中删除toRemove这个数
public void remove(int toRemove){
if(isEmpty()||!contains(toRemove)){
return;
}else{
for (int i = search(toRemove); i <this.usedSize-1 ; i++) {
this.elem[i]=this.elem[i+1];
}
this.usedSize--;
}
}
//判断顺序表中是否包含toFind这个数
public boolean contains(int toFind) {
for (int i = 0; i <this.usedSize ; i++) {
if(toFind==this.elem[i]){
return true;
}
}
return false;
}
//查找返回toFind数的下标,没找到返回-1
public int search(int toFind){
for (int i = 0; i <this.usedSize ; i++) {
if(toFind==this.elem[i]){
return i;
}
}
return -1;
}
//得到下标为pos的值
public int getPos(int pos){
if(pos<0||pos>this.usedSize){
System.out.println("位置不合法");
return -1;
}else{
return this.elem[pos];
}
}
//返回顺序表的长度
public int size(){
return this.usedSize;
}
//清空顺序表
public void clear(){
this.usedSize=0;
}
//打印顺序表
public void display(){
for (int i = 0; i <this.usedSize ; i++) {
System.out.print(elem[i]+" ");
}
System.out.println();
}
}
TestList类
import java.util.Arrays;
public class TestList {
public static void main(String[] args) {
MyArrayList myArrayList=new MyArrayList();
myArrayList.add(0,3);
myArrayList.add(0,5);
myArrayList.add(2,4);
myArrayList.add(2,6);
myArrayList.add(0,7);
System.out.println(myArrayList.size());
System.out.println(myArrayList.getPos(2));
System.out.println(myArrayList.contains(6));
myArrayList.display();
myArrayList.remove(6);
myArrayList.display();
}
}