顺序表
由一个数组(int[] elem)和一个代表有效数字个数的整数组(int usedSize)成。
代码
class SqlistDemo {//顺序表
private int[] elem;//数组
private int usedSize;//有效的数据个数
public SqlistDemo() {
this(10);//表的原始长度
}
public SqlistDemo(int size) {
this.elem = new int[size];
this.usedSize = 0;
}
}
部分函数如下
判断顺序表是否为满、空
public boolean isFull() {//判满
if(this.usedSize == this.elem.length) {
return true;
}
return false;
}
public boolean isEmpty() {//判空
if(this.usedSize == 0) {
return true;
}
return false;
}
将数据插入顺序表
public boolean insert(int pos,int val) {
if(isFull()) {
this.elem = Arrays.copyOf(this.elem, this.elem.length*2);//长度不够,2倍扩容
//return false;
}
//1、判断pos位置的合法性
if(pos < 0 || pos > this.usedSize) {
return false;
}
//2、挪开pos位置的数据
for (int i = this.usedSize-1; i >= pos ; i--) {
this.elem[i+1] = this.elem[i];
}
//3、放入val
this.elem[pos] = val;
this.usedSize++;
return true;
}
查找顺序表中的数据
public int search(int pos,int key) {
if(pos < 0 || pos >= this.usedSize || isEmpty()) {
return -1;
}
for (int i = pos; i < this.usedSize; i++) {
if(this.elem[i] == key) {
return i;
}
}
return -1;
}
删除顺序表中的数据
public boolean delete(int key) {
int index = search(0,key);
if(index < 0) {
return false;
}
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize--;
return true;
}
将顺序表打印出来
public void show() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
运行检测结果
public class TestSqlistDemo {
public static void main(String[] args) {
SqlistDemo sqlistDemo = new SqlistDemo();
for (int i = 0; i < 10; i++) {
sqlistDemo.insert(i,i);//在i号位置放置数字i
}
sqlistDemo.show();//打印1-9
int index = sqlistDemo.search(0,4);//从0号位置开始查找数字4
System.out.println(index);//打印4
sqlistDemo.delete(5);//删除数字5
sqlistDemo.show();//重新打印
}
}