package com.demo.ch02; import java.util.Objects; /** * Created by hp on 2016/11/14. */ public class SqList implements IList{ Object[] listElem;//线性表存储空间 int curLen;//线性表的当前长度 SqList(int maxSize) { curLen = 0;//置顺序表的当前长度为0 listElem = new Object[maxSize];//为顺序表分配maxSize个存储单元 } //将一个已经存在的线性表置成空表 @Override public void clear() { curLen = 0;//置顺序表的当前长度为0 } //判断线性表中的数据元素个数是否为0,若为0反回true,否则反回false @Override public boolean isEmpty() { return curLen == 0; } //求线性表中的元素个数并返回其值 @Override public int length() { return curLen;//返回顺序表的当前长度 } @Override public Object get(int i) throws Exception { if (i < 0 || i >= curLen) { throw new Exception("第" + i + "个元素不存在"); } return listElem[i]; } //插入 @Override public void insert(int i, Object x) throws Exception { if (curLen == listElem.length) { throw new Exception("顺序表已满"); } if (i < 0 || i > curLen) { throw new Exception("插入位置不合法"); } for (int j = curLen; j > i; j--) { listElem[j] = listElem[j - 1];//插入位置及其之后的数据元素右移一个存储位置 } listElem[i] = x; curLen++; } //删除 @Override public void remove(int i) throws Exception { if (i < 0 || i > curLen) { throw new Exception("删除位置不合法"); } for (int j = i; j < curLen - 1; j++) { listElem[j] = listElem[j + 1];//被删除元素及其之后的数据元素左移一个存储位置 } curLen--; } @Override public int indexOf(Object x) { int j = 0; while (j < curLen && !listElem[j].equals(x)) { j++; } if (j < curLen) { return j; } return -1; } @Override public void display() { for (int i = 0; i < curLen; i++) { System.out.print(listElem[i] + " "); } System.out.println(); } }
java实现顺序表
最新推荐文章于 2021-12-02 17:51:58 发布