##顺序表的实现和基本操作
#顺序表的实现
public class SeqList{
private int length;
private int[] datas;
}
#顺序表的创建和初始化
public SeqList() {
}
public SeqList(int capacity) {
length = 0;
datas = new int[capacity];
}
public SeqList(int capacity, int[] array) {
if (capacity < array.length) {
throw new IndexOutOfBoundsException();
} else {
length = 0;
datas = new int[capacity];
for (int i = 0; i < array.length; i++) {
datas[i] = array[i];
length++;
}
}
}
public void create(int capacity) {
if (datas != null) {
throw new RuntimeException();
} else {
length = 0;
datas = new int[capacity];
}
}
#获取指定下标的元素
public int get(int index) {
if (index <= length && index >= 0) {
return datas[index];
} else {
throw new IndexOutOfBoundsException();
}
}
#指定位置插入元素
public void insert(int index, int element) {
if (index >= length || index < 0) {
throw new IndexOutOfBoundsException();
} else {
if (length + 1 <= datas.length) {
for (int i = length; i > index; i--) {
datas[i] = datas[i - 1];
}
datas[index] = element;
length++;
} else {
System.out.println("表已满,无法插入");
}
}
}
#删除指定下标元素
public void delete(int index) {
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException();
} else {
for (int i = index; i < length - 1; i++) {
datas[i] = datas[i + 1];
}
length--;
}
}
#其他操作
public void add(int element) {
if (datas.length <= length) {
System.out.println("表已满,无法添加");
} else {
datas[length] = element;
length++;
}
}
public boolean isEmpty() {
if (datas == null || (datas.length == 0 && length == 0)) {
return true;
} else {
return false;
}
}
public void clear() {
datas = null;
length = 0;
}
public int length() {
return length;
}
public int getMaxSize() {
return datas.length;
}
#输出顺序表的元素
@Override
public String toString() {
if (length <= 0) {
return null;
} else {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < length; i++) {
if (i == length - 1) {
sb.append(datas[i]);
} else {
sb.append(datas[i] + ",");
}
}
return sb.append("]").toString();
}
}
##代码测试
public class SeqListDemo {
public static void main(String[] args) {
int[] array=new int[]{2,4,8,3,6,1,4};
System.out.println("//创建最大容量为10,指定数组元素的顺序表");
SeqList seqList=new SeqList(10,array);
System.out.print("获取顺序表最大容量:");
int maxSize = seqList.getMaxSize();
System.out.println(maxSize);
System.out.print("获取顺序表元素:");
System.out.println(seqList.toString());
System.out.print("获取顺序表长度:");
System.out.println(seqList.length());
System.out.print("添加元素0:");
seqList.add(0);
System.out.println(seqList.toString());
System.out.print("在第1个数前插入元素10:");
seqList.insert(0,10);
System.out.println(seqList.toString());
System.out.print("获取顺序表长度:");
System.out.println(seqList.length());
System.out.print("获取顺序表第3个数字:");
System.out.println(seqList.get(2));
System.out.println("清空顺序表");
seqList.clear();
System.out.print("顺序表元素:");
System.out.println(seqList.toString());
}
}