package list;
interface List{
public void clear();
public boolean isEmpty();
public int length();
public Object get(int i);
public void insert(int i,Object x);
public void remove(int i);
public int indexOf(Object x);
public void display();
}
class SqList implements List{
public Object[] listElem;
//顺序表当前长度
private int curLen;
//顺序表的最大容量
//public static final int MaxSize = 20;
//构造一个容量为MaxSize的空顺序表函数
public SqList(int MaxSize) {
curLen =0;
listElem = new Object[MaxSize];
}
@Override
public void clear() {
curLen =0;
}
@Override
public boolean isEmpty() {
return curLen==0;
}
@Override
public int length() {
return curLen;
}
@Override
public Object get(int i) {
if (i<0||i>curLen-1) {
try {
throw new Exception("第"+i+"个元素不存在");
} catch (Exception e) {
e.printStackTrace();
}
}
return listElem[i];
}
@Override
public void insert(int i, Object x) {
if (i<0||i>=listElem.length) {
try {
throw new Exception("插入的位置不合法,请重新选择插入位置!");
} catch (Exception e) {
e.printStackTrace();
}
}else{
for(int k=curLen;k>i;k--){
listElem[k]=listElem[k-1];
}
listElem[i]=x;
curLen++;
}
}
@Override
public void remove(int i) {
if (i<0||i>listElem.length-1) {
try {
throw new Exception("删除的位置不合法");
} catch (Exception e) {
e.printStackTrace();
}
}
else {
for(int k =i+1;k<listElem.length;k++){
listElem[k-1]=listElem[k];
}
}
curLen--;
}
@Override
public int indexOf(Object x) {
int i=0;
while(i<curLen&&!listElem[i].equals(x)){
i++;
}
if(i<curLen)
return i;
else
return -1;
}
public int directprior(int i){
int temp=0;
if (i<0||i>listElem.length) {
try {
throw new Exception("前驱不存在");
} catch (Exception e) {
e.printStackTrace();
}
}
else
temp=i-1;
return temp;
}
@Override
public void display()
{
for(int i=0;i<curLen;i++)
System.out.print(listElem[i]+" ");
System.out.println("");
}
}
public class IList{
public static void main(String [] args){
SqList List=new SqList(10);
List.insert(0, 'a');
List.insert(1, 'b');
List.insert(2, 'c');
List.insert(3, 'd');
List.insert(4, 'e');
List.insert(5, 'f');
List.insert(6, 'g');
List.display();
System.out.println("第一次出现e的位置是:");
int order =List.indexOf('e');
System.out.println(order+1);
int key=List.directprior(3);
System.out.println("位置3前面的值是:"+List.listElem[key]);
}
}