package test;
//线性表的顺序存储采用数组的结构
public class SeqList {
private int data[];
private int last;
private int maxSize;
public SeqList(int maxSize) {
// TDO Auto-generated constructor stub
last = -1;
this.maxSize = maxSize;
data = new int[maxSize];
}
// 在位置index(在数组中的下标为location-1)插入元素x
public boolean insert(int location, int x) {
// 检查是否有剩余空间
if (last == maxSize - 1){
return false;
}
int index=location-1;
// 检查插入的位置是否正确
if (index < 0 || index > last + 1){
return false;
}
for (int i = last; i >= index; i--) {
data[i + 1] = data[i];
}
data[index] = x;
last++;
return true;
}
// 按值删除,先查找
public boolean delete(int x) {
boolean flag = false;
int index = location(x);
System.out.println("index:"+index);
if (index != -1) {
for (int i = index; i
data[i] = data[i + 1];
}
last--;
flag = true;
}
return flag;
}
// 按位置删除(下标为位置-1)
public boolean deleteLocation(int loction) {
int index=loction-1;//位置在数组中的下标
if (index < 0 || loction > last) {// 检查删除位置的合法性
return false;
}
for (int i = index; i < last; i++) {
data[i] = data[i + 1];
}
last--;
return true;
}
// 查找x在线性表中的位置下标从0开始
public int location(int x) {
for (int i = 0; i <= last; i++) {
if (data[i] == x)
return i;
}
return -1;
}
public void show() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i <= last; i++) {
if (i != last)
sb.append(data[i] + ",");
else
sb.append(data[i]);
}
sb.append("]");
System.out.println(sb.toString());
}
public static void main(String[] args) {
SeqList s = new SeqList(40);
for (int i = 1; i <= 5; i++) {
s.insert(i, i+1);
}
s.show();
s.deleteLocation(3);
s.show();
}
}