栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

java-顺序表

Java 更新时间:发布时间: 百科书网 趣学号
 public class MyArrayList {
    public int[] elem;//数组
    public int usedSize;//有效的数据个数
    public static final int capacity = 10;//初始容量

    public MyArrayList() {
        this.elem = new int[capacity];
        this.usedSize = 0;
    }

//检查elem是否满了
    private boolean isFull() {
        if (this.usedSize == this.elem.length) {
            return true;
        }
        return false;
    }

    //检查pos是否合法
    private void checkPos(int pos) {
        if (pos < 0 || pos > this.usedSize) {
            throw new RuntimeException("pos位置不合法!");
        }
    }

    //1.在pos位置插入元素
    public void add(int pos, int data) {
        //数组二倍扩容
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * elem.length);
        }
        //检查pos是否合法
        checkPos(pos);
        //开始挪元素
        for (int i = this.usedSize - 1; i >= pos; i-- ){
            this.elem[i + 1] = this.elem[i];
        }
        this.elem[pos] = data;//插入元素
        this.usedSize += 1;//有效元素个数+1

    }

    //2.打印顺序表
    public void display(){
       for (int i = 0;i < this.usedSize;i++) {
           System.out.print(this.elem[i]+" ");
       }
        System.out.println();
    }

    //3.判定顺序表中是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0;i < usedSize;i++){
            if (this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    //4.查找某个元素对应的位置
    public int search(int toFind) {
        for (int i = 0;i < usedSize;i++){
            if (this.elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    //5. 获取pos位置的元素
    public boolean isEmpty(){
        return this.usedSize == 0;
    }

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

    //6.获取顺序表长度
    public int size() {
        return this.usedSize;
    }

    //7.删除第一次出现的关键字key
    public void remove(int toRemove) {
        //判断是否有key
        if (search(toRemove) == -1) {
            System.out.println("没有需要删除的数字");
            return;
        }
        for (int i = this.getPos(toRemove); i < this.usedSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.usedSize--;
    }

    //8.清空顺序表
    public void clear(){
        this.usedSize = 0;
    }

    //9.把pos位置的元素设置为value
    public void setPos(int pos,int value) {
        if (pos < 0 || pos >= usedSize){
            throw new RuntimeException("pos位置不合法!");
        }
        this.elem[pos] = value;
    }
 }

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/273324.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号