JAVA数据结构之线性表的顺序存储

来源:互联网 发布:百度搜索关键词优化 编辑:程序博客网 时间:2024/06/18 13:34

用JAVA实现线性表的顺序存储结构的代码如下所示:

public class SeqList {private Object array[];private int capacity;//顺序表的容量,即顺序表中能保存的元素的个数。private int length;//顺序表中现有元素的个数。public SeqList(int capacity){array = new Object[capacity];this.capacity = capacity;this.length = 0;}//插入元素public void insert(Object obj) throws Exception{if(length < capacity){array[length] = obj;length++;}else{throw new Exception("顺序表已满!");}}//插入元素public void insert(Object obj,int index) throws Exception{if(index < 0){throw new Exception("插入元素的下标已越界");}else if(length + 1 > capacity){throw new Exception("顺序表已满,插入失败!");}else{if(index >= length){index = length;}for(int i = length;i > index;i--){array[i] = array[i - 1];}array[index] = obj;length++;}}//删除元素public void delete(int index) throws Exception{if(index < 0 || index >= length){throw new Exception("要删除元素的下标已越界");}else{array[index] = null;for(int i = index;i < length - 1;i++){array[i] = array[i + 1];}length--;}}//清空顺序表中的元素public void clear(){for(int i = 0;i < length;i++){array[i] = null;}length = 0;}//销毁顺序表public void destroy(){array = null;capacity = 0;length = 0;}//获取顺序表的长度public int getLength(){return length;}//获取顺序表的容量public int getCapacity(){return capacity;}//判断顺序表是否为空public boolean isEmpty(){return length == 0;}//获取顺序表中指定下标的元素public Object getObject(int i) throws Exception{if(i < 0 || i >= length){throw new Exception("要获取的元素的下标已越界");}else{return array[i];}}//获取顺序表中指定元素的下标public int indexOfObject(Object obj){int ret = 0;while(ret < length && !array[ret].equals(obj)){ret++;}if(ret >= length){ret = -1;}return ret;}//打印顺序链表中的元素public void display(){for(int i = 0;i<length;i++){System.out.print(array[i]+"  ");}System.out.println();}}
测试上述顺序表的代码如下所示:

public class Test {public static void main(String[] args) {SeqList seqList = new SeqList(5);try {seqList.insert("元素1");seqList.insert("元素2");seqList.insert("元素3");seqList.insert("元素4");seqList.insert("元素5");} catch (Exception e) {e.printStackTrace();}System.out.println("顺序表的容量:"+seqList.getCapacity());System.out.println("顺序表中元素的个数:"+seqList.getLength()+"--顺序表是否为:"+seqList.isEmpty());seqList.display();System.out.println("“元素1”的下标:"+seqList.indexOfObject("元素1"));try {System.out.println("顺序表中的下标为3的元素:"+seqList.getObject(3));} catch (Exception e) {e.printStackTrace();}try {seqList.delete(3);} catch (Exception e) {e.printStackTrace();}System.out.println("删除下标为3的元素后:");seqList.display();seqList.clear();System.out.println("清除所有元素后:"+"--顺序表是否为:"+seqList.isEmpty());seqList.display();seqList.destroy();System.out.println("销毁顺序表后,顺序表的容量:"+seqList.getCapacity()+"--顺序表中元素的个数:"+seqList.getLength()+"--顺序表是否为:"+seqList.isEmpty());seqList.display();}}