顺序表
1. 顺序表接口的实现
public class SeqList {
private int[] array;
public static final int Current_Max=5; //当前数组元素最大值
private int UsedSize; //记录当前顺序表中有多少个有效的数据
public SeqList() {
this.array = new int[Current_Max];
}
}
2. 顺序表方法
//_新增元素,默认在数组最后新增
public void add(int data) { }
// 在 pos 位置新增元素
public void add(int pos, int data) { }
// 判定是否包含某个元素
public boolean contains(int toFind) { return true, }
// 查找某个元素对应的位置
public int indexOf(int toFind) { return -1; }
// 获取 pos 位置的元素
public int get(int pos) { return -1; }
// 给 pos 位置的元素设为 value
public void set(int pos, int value){ }
//删除第一次出现的关键字key
public void remove(int toRemove){}
// 获取顺序表长度
public int size() { return 0; }
// 清空顺序表
public void clear() {}
// 打印顺序表,注意:该方法并不是顺序表中的方法,为了方便看试结果给出的
public void display(){}
-
3.方法的实现
3.1打印数组
遍历数组
public static void DisPlay(){
for(int i=0;i<SeqList.Current_Max;i++){
System.out.printf(array[i]+" ");
}
3.2 新增元素
默认在数组最后新增
public void add(int data) { }
public static void add(int data){
array[UsedSize]=data;
UsedSize++;
}
注意!!!此处仅仅这样写存在逻辑上的错误
!!想要新增元素,需要判断顺序表是否已满!!
3.2.1判满
//判断顺序表是否已满
public boolean Isfull(){
return UsedSize == array.length;
}
这个方法会检查 UsedSize(已使用元素的数量)是否等于 array.length(数组的容量)。如果两者相等,那么顺序表(或者更具体地说,是数组实现的线性表)就已经满了,方法会返回 true;否则,返回 false。
3.2.2扩容
如果数组已满,需要对已有数组扩容,扩容后即可新增数组元素。
array= Arrays.copyOf(array,2*array.length);
Arrays.copyOf(array, 2 * array.length) 是 Java 中一个常用的方法,用于将数组 array 扩容到原来的两倍大小。这个方法会创建一个新的数组,其长度为原数组长度的两倍,并将原数组的元素复制到新数组中。然后,你可以将新数组赋值给原数组的引用变量,从而实现了数组的扩容。
3.2.3新增数组元素
public void add(int data){
if(isFull()){
array= Arrays.copyOf(array,2*array.length);
}
array[UsedSize]=data;
UsedSize++;
}
提供的 add 方法是一个向顺序表中添加整数元素的示例,该方法在顺序表满时会扩容。
3.3 获取 pos 位置的元素
public int get(int pos){
if(pos<0||pos>=UsedSize){
throw new PosOutBoundsException("获取数据时,位置不合法!");
}
return array[pos];
}
3.3.1判断pos位置是否合法
throw new PosOutBoundsException("获取数据时,位置不合法!")
自定义异常
public class PosOutBoundsException extends RuntimeException {
public PosOutBoundsException() {
}
public PosOutBoundsException(String message) {
super(message);
}
}
3.4判定是否包含某个元素
public boolean contains(int toFind) { return true, }
public boolean contains(int toFind){
for(int i=0;i<SeqList.Current_Max;i++)
{
if(toFind==array[i]){
return true;
}
}
return false;
}
3.5查找某个元素对应的位置
public int indexOf(int toFind) { return -1; }
public int indexOf(int toFind){
for(int i=0;i<SeqList.Current_Max;i++)
{
if(toFind==array[i]){
System.out.printf("该元素对应下标为"+i+"\n");
}
}
return -1;
}