数据结构——顺序表

一、顺序表原理

线性表的顺序存储结构称为顺序表

顺序表是用一段地址连续的存储单元依次存储线性表的数据元素。由于线性表中的每个数据元素的类型相同,通常用一维数组来实现顺序表。

二、顺序表实现

package com.demo.seqlist;

public class SeqList {

    private int maxSize;
    private int size;
    private Object[] arrayList;
    
    public SeqList(int size){
        maxSize = size;
        size = 0;
        arrayList = new Object[size];
    }
    
    public void insert(int i,Object obj) throws Exception{
        if(size == maxSize){
            throw new Exception("顺序表已满,无法继续插入");
        }
        
        if(i<0 || i>size){
            throw new Exception("插入位置不存在");
        }
        
        for(int j = size; j>i; j--){
            arrayList[j] = arrayList[j-1];
        }
        arrayList[i] = obj;
        size++;
    }
    
    public Object delete(int i) throws Exception{
        if(size == 0){
            throw new Exception("顺序表已空");
        }
        
        if(i<0 || i>size){
            throw new Exception("删除位置不存在");
        }
        
        Object obj = arrayList[i];
        for(int j=i; j<size; j++){
            arrayList[j] = arrayList[j+1];
        }
        size--;
        return obj;
    }
    
    public int getSize(){
        return size;
    }
    
    public Object getData(int i){
        return arrayList[i];
    }
}

 

posted @ 2018-02-08 21:22  取什么昵称呢  阅读(146)  评论(0编辑  收藏  举报