package com.ncu.list; /** * * 顺序结构线性列表 * * @author liuhao * */ public class SquenceList<T> { private int size; // 线性表的长度 private Object[] listArray; private int currenSize = 0; // 当前线性表中的数据 public SquenceList() { } public SquenceList(int size) { this.size = size; listArray = new Object[size]; } public void arrayCopy(int index) { Object newArray[] = new Object[size]; for (int i = 0; i < currenSize; i++) { if (i >= index) { newArray[i] = listArray[i + 1]; } else { newArray[i] = listArray[i]; } } listArray = newArray; newArray = null; // 释放资源 } /** * 根据索引位置移除元素 * * @param index */ public void remove(int index) { index = index - 1; if (index < 0 || index > currenSize) { System.out.println("线性表索引越界"); } if (currenSize == 0) { System.out.println("线性表为空"); } else { currenSize--; arrayCopy(index); if (currenSize == 0) { listArray = null; } } } /** * 根据元素内容移除元素 * * @param element */ public void removeLocate(T element) { for (int i = 0; i < currenSize;) { if (element.equals(listArray[i])) { remove(i + 1); } else { i++; } } } /** * 从线性表尾段插入数据 * * @param element */ public void add(T element) { if (currenSize > size || currenSize < 0) { System.out.println("线性表索引越界"); } else { listArray[currenSize] = element; currenSize++; } } private void insert(T element, int index) { index = index - 1; if (currenSize > size || currenSize < 0 || index < 0 || index >= currenSize) { System.out.println("线性表索引越界"); } else { Object newArray[] = new Object[size]; for (int i = 0; i < currenSize; i++) { if (i >= index) { newArray[index] = element; newArray[i + 1] = listArray[i]; } else { newArray[i] = listArray[i]; } } listArray = newArray; newArray = null; currenSize++; } } /** * 在指定索引位置插入数据 * * @param element * @param index */ public void add(T element, int index) { if (index == size) { add(element); } else { insert(element, index); } } /** * 删除线性表最后一个元素 */ public void delete() { if (isEmpty()) { System.out.println("线性表为空,不能删除"); } else { listArray[currenSize - 1] = null; currenSize--; } } /** * 判读线性表是否为空 * * @return */ public boolean isEmpty() { if (currenSize == 0) { return true; } else { return false; } } /** * 根据索引找到相应的元素 * * @param index * @return */ public T get(int index) { T obj = null; if (isEmpty() || index > currenSize || index < 0) { System.out.println("线性表为空,不能删除"); } else { obj = (T) listArray[index - 1]; } return obj; } /** * 清空线性表 */ public void clear() { size = 0; currenSize = 0; } /** * 得到线性表当前的元素的个数 * * @return */ public int size() { return currenSize; } public void showList() { if (currenSize > 0) { for (int i = 0; i < currenSize; i++) { System.out.println(listArray[i]); } } else { System.out.println("线性表为空"); } System.out.println("------------"); } public static void main(String[] args) { SquenceList<Integer> list = new SquenceList<Integer>(10); } }