线性表的数组实现(Java实现)

为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++;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值