顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
顺序表一般可以分为: 静态顺序表:使用定长数组存储。 动态顺序表:使用动态开辟的数组存储。
下面我们来进行顺序表接口的实现。
定义顺序表的一个类。
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;
}
}
类的方法
1.打印顺序表
通过遍历顺序表,打印每个下标的值。
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.println(this.elem[i] + "");
}
System.out.println();
}
2.在pos位置处增加新的元素
首先要判断顺序表的长度是否跟有效长度一样,再判断一次pos的合法性。
如果长度是一样的,那么就要让顺序表的长度扩大一倍,用来插入新的元素。
pos位置不合法,抛出异常。pos合法,进入挪顺序表的数据。从后到pos位置遍历数组,让i=this.usedSize - 1,this.elem[i + 1] = this.elem[i]。一个个往后挪数据。最后让 this.elem[pos] = data;有效长度+1.
private boolean isFull() {
/* if(this.usedSize == this.elem.length) {
return true;
}
return false;*/
return this.usedSize == this.elem.length;
}
private void checkPos(int pos) {
if (pos < 0 || pos > this.usedSize) {
throw new RuntimeException("pos位置不合法!");
}
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
checkPos(pos);
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++;
}
3.判定是否包含某个元素
遍历这个顺序表,如果某个元素的值等于要查找的值,则返回true,没有返回false。
public boolean contains(int toFind){
for(int i=0;i<=this.usedSize;i++){
if (this.elem[i]==toFind){
return true;
}
}
return false;
}
4.查找某个元素对应的位置
遍历这个顺序表,如果某个元素的值等于要查找的值,则返回下标,没有返回-1。
public int seach(int toFind){
for(int i=0;i<=this.usedSize;i++){
if(this.elem[i]==toFind){
return i;
}
}
return -1;
}
5.获取 pos 位置的元素
首先写一个判断当前列表是否为空的方法isEmpty。
输入pos位置,调用isEmpty方法,如果为空,手动抛出异常。在判断pos位置的合法性。
最后在返回pos位置的元素。
private boolean isEmpty() {
return this.usedSize == 0;
}
// 获取 pos 位置的元素
public int getPos(int pos){
if(isEmpty()){
throw new RuntimeException("顺序表为空");//手动抛出异常
}
if(pos<0||pos>=this.usedSize){
throw new RuntimeException("顺序表为空");//手动抛出异常
}
return this.elem[pos];
}
6.获取顺序表长度
public int size(){
return this.elem.length;
}
7.删除第一次出现的关键字toRemove
首先调用上面写的seach方法,判断有没有这个元素,没有输出“找到不需要删除的数字!”。如果找到这个元素,返回下标,从这个下标开始,遍历顺序表,让后面的元素一个个覆盖到前面的元素,最后让有效长度-1.
public void remove(int toRemove){
int index=seach(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--;
}
8.更新pos位置的元素
首先还是要判断pos的合法性,不合法输出“pos位置不合法!”,合法的情况下,把value赋值给pos下标。
public void setPos(int pos, int value){
if(pos<0||pos>=this.usedSize){
throw new RuntimeException("pos位置不合法!");
}
this.elem[pos] = value;
}
9.清空顺序表
让有效长度等于0即可。
public void clear(){
this.usedSize = 0;
}