顺序表
顺序表由一个数组和一个代表有效数字个数的整数组成。
用java实现一个顺序表
需要的数据结构:
- 一个int类型的数组:int[] elem
- 表示数组有效数据的个数: int usedSize
需要的函数:
- 判断顺序表是否为满:public boolean isFull()
- 向顺序表中插入数据:public boolean insert(int pos,int val) →pos:下标,val:插入的数据
- 判断顺序表是否为空:public boolean isEmpty()
- 查找顺序表中的元素: public int search(int pos,int key)→key:需要查找的值
- 删除顺序表中的元素:public boolean delete(int key)
- 打印顺序表:public void show()
代码:
import java.util.Arrays;
/**
* @auther: 巨未
* @DATE: 2019/1/28 0028 19:20
* @Description: 顺序表
*/
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 insert(int pos,int val) {
if(isFull()){
this.elem = Arrays.copyOf(this.elem,this.elem.length*2);//2倍扩容
// return false;
}
//1.判断pos位置合法性 (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 boolean isEmpty(){
if(this.usedSize == 0) {
return true;
}
return false;
}
//查找
public int serach(int pos,int key) { //从pos位置(判断pos位置是否合法)然后开始查找key的值并返回下标
if (isEmpty()) {
System.out.println("链表为空!");
return -1;
}
if (pos < 0 || pos >= this.usedSize) {
return -1;
}
for (int i = pos; i < this.usedSize; i++) {
if (elem[i] == key) { //注意等号的应用,equals
return i;
}
}
return -1;
}
//删除
public boolean delete(int key) {
if (isEmpty()) {
return false;
}
int index = serach(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);
}
sqlistDemo.show();
int index = sqlistDemo.serach(0,4);
System.out.println(index);
sqlistDemo.delete(4);
sqlistDemo.show();
}
}
实现结果:
- 第一行:插入0-9十个数字后打印顺序表
- 第二行:打印出数字4的下标
- 第三行:删除数字4后打印顺序表