顺序表: 顺序表比较简单,就是创建一个数组,顺序存储某一类型的数据,
* @Author : WHVO
*
* @Description:
*
* @Date: Created in 19:05 2018/11/21/021
*
* @Modified By: 顺序表
*
*/
import java.util.Arrays;
public class testSqlist {
private int[] elem;
private int size;
public testSqlist() {
this(10);
}
public testSqlist(int size) {
elem = new int[size];
}
// 检查是否满了
public boolean isFill() {
return size == elem.length;
}
//根据索引插入数据
public boolean insert(int index, int val) {
//扩容
if (isFill()) {
Arrays.copyOf(elem, 2 * elem.length);
}
// 检查索引
if (index < 0 || index > size) {
return false;
} else {
for (int i = size - 1; i >= index; i--) {
//数字后移
elem[i + 1] = elem[i];
}
elem[index] = val;
size++;
return true;
}
}
//是否为空
public boolean isEmpty() {
return size == 0;
}
//查找关键字下标
public int serach(int key) {
if (isEmpty()) {
return -1;
} else {
for (int i = 0; i < size; i++) {
if (this.elem[i] == key) {
return i;
}
}
}
return -1;
}
//删除关键字key的值;
public boolean remove(int key) {
int index = serach(key);
if (index == -1) {
return false;
} else {
for (int j = index; j < this.size - 1; j++) {
elem[j] = elem[j + 1];
}
this.size--;
return true;
}
}
// 得到索引位置的值
public Object getVal(int pos) {
if (pos < 0 || pos > size || isEmpty()) {
throw new UnsupportedOperationException();
} else {
return elem[pos];
}
}
public String toString() {
return Arrays.toString(elem);
}
}