Java实现顺序表

一、什么是顺序表?

顺序表就是用一组地址连续的存储单元存储各个元素,使得其在逻辑上相邻,物理上也相邻,以数组的形式保存数据。

二、顺序表的常见操作:

1.创建类和构造方法

public class MyArrayList {
    private int [] elem;
    private int usedSize;

    public MyArrayList(){
        this.elem = new int [10];
    }

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

2.扩容

    public void resize(){
        this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
    }

3.判断顺序表是否为满

      public boolean isFull(){
        if(this.usedSize == this.elem.length){
            return true;
        }
        return false;
    }

4.打印顺序表

    public void display() {
        for (int i = 0;i < usedSize; i++) {
            System.out.print(elem[i]+"  ");
        }
        System.out.println();
    }

5.在pos位置新增元素

    public void add(int pos, int data) {
        if(isFull()){
            System.out.println("链表已满!");
            resize();
        }
        if(pos < 0 || pos > this.usedSize){
            System.out.println("插入位置不合法!");
            return;
        }
        for (int i =  usedSize-1; i >= pos;i--) {
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        this.usedSize++;
    }

6.判断是否包含某个元素

    public boolean contains(int toFind) {
        for(int i = 0; i < usedSize;i++){
            if(elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

7.查找某个元素对应的位置

    public int search(int toFind) {       
        for(int i = 0; i < usedSize;i++){
            if(elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

8.获取pos位置的元素

    public int getPos(int pos) {   
        if(pos < 0 || pos >= usedSize){
            System.out.println("该pos位置不合法!");
            return -1;
        }
        return elem[pos];
    }

9.给pos位置的元素修改为value

    public void setPos(int pos, int value) {    
        if(pos < 0 || pos >= usedSize){
            System.out.println("该pos位置不合法!");
            return;
        }
        elem[pos] = value;
    }

10.删除第一次出现的关键字Key

    public void remove(int toRemove) {    
        int index = -1;
        for(int i = 0; i < this.usedSize;i++){
            if(this.elem[i] == toRemove){
                index = i;
            }
        }
        if(index == -1){
            System.out.println("未找到该元素!");
            return;
        }
        for(int j = index;j < this.usedSize-1;j++){
            this.elem[j] = this.elem[j+1];
        }
        this.usedSize--;
    }

11.获取链表长度

    public int size() {    
        return this.usedSize;
    }

12.清空顺序表

      public void clear() {
        this.usedSize = 0;
    }
  • 11
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值