1.顺序表概念
顺序表是用一段物理地址连续的存储单元一次存储数据元素的线性结构,一般采用数组存储,在数组上完成数据的增删改查
顺序表一般可以分为:使用定长数组存储
适用于确定知道需要多少存储空间的情况
使用动态开辟的数组存储
灵活的开辟内存空间
2.简单顺序表代码示例
import java.util.Arrays;
public class MyArrayList {
private int[] elem ;
private int usedSize;
public MyArrayList(int num){
this.elem=new int[num];
}
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 contain( int t){
for (int i = 0;i<this.usedSize;i++){
if (this.elem[i]==t){
return true;
}
}
return false;
}
//寻找某个元素并返回其下标,若没有此元素返回-1
public int search(int t){
if (this.contain(t)==false){
return -1;
}
for (int i=0;i<this.usedSize;i++){
if (this.elem[i]==t){}
return i;
}
return -1;
}
//获取某个位置的元素
public int getValue(int pos){
if (pos<0||pos>this.usedSize){
System.out.println("此位置不合法");
return -1;
}
return this.elem[pos];
}
//重置某个位置的元素
public void setPos(int pos,int t){
if (pos<0||pos>=this.usedSize){
System.out.println("此位置不合法");
return;
}
this.elem[pos]=t;
}
//给顺序表添加元素
public void add(int t){
if (this.elem.length==this.usedSize){
this.elem= Arrays.copyOf(this.elem,2*this.elem.length);
}
this.elem[this.usedSize]=t;
this.usedSize++;
}
//在指定位置添加元素
public void add(int pos,int t){
if (pos ==this.usedSize){
this.add(t);
return;
}
if (pos<0||pos>this.usedSize){
System.out.println("此位置不合法");
return;
}
if (this.elem.length==this.usedSize){
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]=t;
this.usedSize++;
}
//获取指定元素的位置
public int getPos(int t){
for (int i=0;i<usedSize;i++){
if (this.elem[i]==t){
return i;
}
}
return -1;
}
//删除某个位置的元素,
public void remove(int pos){
if (pos<0||pos>this.usedSize){
System.out.println("此位置不合法");
return;
}
for (int i =pos;i<this.usedSize;i++){
this.elem[i]=this.elem[i+1];
}
this.usedSize--;
}
//清空顺序表
public void clear(){
for (int i =this.usedSize;i>0;i--){
this.elem[i-1]=this.elem[i];
}
}
}
3.测试示例
public class Demo {
public static void main(String[] args){
MyArrayList A = new MyArrayList(8);
A.add(0,9);
A.add(10);
A.add(41,5);
A.add(6);
A.add(50);
A.contain(5);
System.out.println(A.getPos(50));;
A.getValue(6);
A.setPos(A.getPos(50),40);
A.display();
A.size();
A.clear();
A.display();
}
}