顺序表的特点:
1.中间或前面部分的插入删除时间复杂度O(N)
2.增容的代价比较大
链表的特点:
1.任意位置插入删除时间复杂度为O(1)
2.没有增容问题,插入一个开辟一个空间。
顺序表就是一个数组,如下代码就是使用数组实现一个单链表。
import java.util.Arrays;
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;
}
//打印顺序表
public void display(){
for(int i = 0; i < this.usedSize;i++){
System.out.print(this.elem[i]+" ");
}
}
private void checkPos(int pos){
if(pos < 0 || pos > this.usedSize){
throw new RuntimeException("pos位置不合法!");
}
}
private boolean isFull(){
// if(this.usedSize == this.elem.length){
// return true;
// }
// return false;
return this.usedSize == this.elem.length;
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
if(isFull()){
//如果满了 数组扩容 原来的销毁
this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
}
//在pos位置新增元素
// if(pos < 0 || pos > this.usedSize){
// System.out.println("Error");
// return;
// }
checkPos(pos);
//挪数据
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;
}
// 获取 pos 位置的元素
// 1.顺序表是否为空,为空返回-1
// 2.pos合法性 最后return pos位置的数据就ok
private boolean isEmpty(){
return this.usedSize == 0;
}
public int getPos(int pos) {
//1.顺序表是否为空,为空返回-1
// if(isEmpty()){
// return -1;
// }
//2.pos合法性
if(pos < 0 || pos >= this.usedSize){
return -1;
}
// for(int i = 0; i < this.usedSize; i++){
// if(i == pos){
// return this.elem[i];
// }
// }
// return -1;
return this.elem[pos];
}
//删除第一次出现的关键字key
public void remove(int toRemove) {
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;
}
// 给 pos 位置的元素设为 value
public void setPos(int pos,int value){
if(pos < 0 || pos >= this.usedSize){
throw new IndexOutOfBoundsException("pos位置不合法!!!");
}
this.elem[pos] = value;
}
//清空数据表
public void clear(){
this.usedSize = 0;
}
public static void main(String[] args) {
MyArrayList myArrayList = new MyArrayList();
for(int i = 0; i < 10; i++){
myArrayList.add(i,i);
}
myArrayList.display();
System.out.println();
myArrayList.add(10,25);
myArrayList.display();
System.out.println();
System.out.println("=========================");
System.out.println(myArrayList.search(5));
System.out.println(myArrayList.contains(5));
myArrayList.remove(38);
myArrayList.display();
// System.out.println("clear()");
// myArrayList.clear();
// myArrayList.display();
myArrayList.setPos(10,6);
myArrayList.display();
}
}