顺序表

线性表:n个具有相同特性的数据元素的集合;顺序表,链表,栈,队列,字符串……

顺序表定义:顺序表使用一段物理地址连续的存储单元依次存储数据元素的数据结构
在数组上完成增删查改

分类:
静态数据表:使用定长数组存储
动态数据表:使用动态开辟的数组存储

 public  int[]   elem;
    public  int usedSize;//有效元素的个数
    public   static   final  int capacity=10;

    MyArrayList(){
        this.elem=new  int[capacity];
        this.usedSize=0;
private   boolean  ifFull(){
        if(usedSize==capacity){
            return  true;
        }
        return  false;
    }
     private  void  checkPos(int pos){
         if(pos<0||pos>usedSize){
             throw new  RuntimeException("pos位置不合法");
         }
     }
//增加元素  判断pos位置是否合法pos<=uesdSize      挪数据      放数据,usedSize++
    public  void   add(int pos,int data){
            checkPos(pos);
             if(ifFull()){
                 this.elem= Arrays.copyOf(this.elem,this.elem.length*2);
             }
            int i = 0;
            for (i = usedSize - 1; i>=pos; i--) {
                this.elem[i + 1] = this.elem[i];
            }
            this.elem[pos] = data;
            this.usedSize++;
    }
 //打印顺序表
    public  void  display(){
        for(int i=0;i<usedSize;i++){
            System.out.print(this.elem[i]+" ");
        }
  //是否包含某个元素
     public  boolean   contains(int  toFind){
        for(int i=0;i<this.usedSize;i++){
            if(this.elem[i]==toFind){
                return  true;
            }
        }
        return   false;
     }

  //toFind的下标
     public  int search(int toFind){
         for(int i=0;i<this.usedSize;i++){
             if(this.elem[i]==toFind){
                 return  i;
             }
         }
        return -1;
     }

 //pos位置的元素
      public int  getPos(int pos){
             if(usedSize==0){
                 throw  new   RuntimeException("顺序表为空");
             }
           if(pos<0||pos>=usedSize){
               throw  new  RuntimeException(" pos位置不合法!!!");
           }
        return   this.elem[pos];
      }

//有效元素的个数
     public  int  size(){
        return  usedSize;
     }

//删除第一次出现的关键字toRemove
     public  void  remove(int toRemove){
          int a=search(toRemove);
          if(a==-1){
              System.out.println("没有需要删除的数字");
              return;
          }
         for(int i=a;i<usedSize-1;i++){
             elem[i]=elem[i+1];
         }
        usedSize--;
     }
//清空
     public void clear(){
       this.usedSize=0;
     }
//更新pos位置的元素
     public void  setPos(int pos,int  data){
        if(pos<0||pos>=usedSize){
            throw  new  RuntimeException("位置不合法");
        }
        this.elem[pos]=data;
     }

增容需要申请新空间,拷贝数据,释放旧空间;
增容一般呈2倍增长,势必会造成空间的浪费

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值