1.顺序表采用顺序存储的方式,所以内部采用数组来实现
2.由于存储类型不一定,所以在这里采用的是泛型来实现
public class List<E> { private Object[] o; private int subscript; /** * 初始化线性表 * * @Title: initList * @Description: <ul> * <li>初始化长度为10</li> * <li>初始化下标为0</li> * </ul> * @return void */ public void initList() { this.o = new Object[10]; this.subscript = 0; } /** * 判断线性表是否为空 * * @Title: isEmpty * @Description: * @return boolean */ public boolean isEmpty() { return this.o == null ? true : false; } /** * 清空线性表 * * @Title: clearList * @Description: */ public void clearList() { this.o = null; this.subscript = 0; } /** * 获取索引处的元素 * * @Title: getElem * @Description: * @param index * @return E */ @SuppressWarnings("unchecked") public E getElem(int index) { this.validateList(index); // Msg.info(this.o[index]); return (E) this.o[index]; } /** * 验证索引是否合法 * * @Title: validateList * @Description: * @param index */ private void validateList(int index) { if (index > this.length() || index < 0) { throw new RuntimeException("线性表索引异常:" + index); } } /** * 验证线性表里是否存在元素e * * @Title: locateElem * @Description: * @param e * @return boolean */ public boolean locateElem(E e) { boolean flag = false; for (int i = 0; i < this.length(); i++) { if (this.getElem(i).equals(e)) { flag = true; } } return flag; } /** * 向线性表指定的索引处插入e * * @Title: insert * @Description: * @param index * @param e */ public void insert(int index, E e) { if (this.isEmpty()) { this.initList(); } this.validateList(index); Object[] tmp; if (this.length() >= this.o.length) { tmp = new Object[this.length() + 10]; } else { tmp = new Object[this.o.length]; } for (int i = 0; i <= this.length(); i++) { if (i < index) { tmp[i] = this.getElem(i); } else if (i == index) { tmp[i] = e; } else { tmp[i] = this.getElem(i - 1); } } this.o = tmp; this.subscript++; } /** * 删除指定索引处的元素 * * @Title: delete * @Description: * @param index * @return E */ public E delete(int index) { this.validateList(index); E e = null; Object[] tmp = new Object[this.o.length]; for (int i = 0; i < this.length(); i++) { if (i < index) { tmp[i] = this.getElem(i); } else if (i == index) { e = this.getElem(i); } else { tmp[i - 1] = this.getElem(i); } } this.o = tmp; this.subscript--; return e; } /** * 获取线性表的长度 * * @Title: length * @Description: * @return int */ public int length() { return this.subscript; } }
内部采用的是数组实现线性表:
优点:
在查找元素的时候,直接通过数组下标进行查找,速度较快!
缺点:
- 插入元素和删除元素时则需要移动大量的元素,费时费力。
- 数组在申明时,就需要对长度进行定义,若元素超过数组容量,则需重新申明数组,同时要需复制当前所有数据。
浙公网安备 33010602011771号