为SqList类增加以下的函数:
1、实现public void removeRange(int from, int to),删除位置为[from, to]的所有数据。
2、设顺序表中的数据元素递增有序。实现public void insertSortedList(T x),将x插入到顺序表的适当位置上,以保持该表的有序性。
public interface IList{
public int length();
public void display();
public void insert(int i,int x);
public void removeRange(int from,int to)throws Exception;
public void insertSortedList(int x)throws Exception;
}
/*
1.线性表的数组实现
为SqList类增加以下的函数:
1、实现public void removeRange(int from, int to),删除位置为[from, to]的所有数据。
2、设顺序表中的数据元素递增有序。实现public void insertSortedList(T x),将x插入到顺序表的适当位置上,以保持该表的有序性。
*/
public class SqList implements IList{
private int[] listElem;
private int curlen;
public SqList(int maxSize) {
curlen=0;
listElem=new int[maxSize];
}
public int length(){
return curlen;
}
public void display(){
for(int j=0;j<curlen;j++){
System.out.print(listElem[j]+" ");
}
System.out.println();
}
public void insert(int i,int x){
for (int j=curlen;j>i;j--)
listElem[j]=listElem[j-1];
listElem[i]=x;
curlen++;
}
//1.1
public void removeRange(int from,int to)throws Exception{
if(from>to||from<0||from>curlen-1||to>curlen-1)
throw new Exception("删除区间不合法");
int f=from;
for(int j=to+1;j<=curlen-1;j++){
listElem[from]=listElem[j];
from++;
}
curlen=curlen-to+f-1;
}
//1.2
public void insertSortedList(int x)throws Exception{
if(curlen==listElem.length)
throw new Exception("顺序表已满");
int j,i=0;
while(listElem[i]<x&&i<curlen){
i++;
}
for(j=curlen;j>i;j--){
listElem[j]=listElem[j-1];
}
listElem[i]=x;
curlen++;
}
}