Java的顺序表的创建及对顺序表进行相关的操作
1.顺序表的定义:
顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元依次存储线性表中的各个元素、使得线性表中在逻辑结构上相邻的数据元素存储在相邻的物理存储单元中,即通过数据元素物理存储的相邻关系来反映数据元素之间逻辑上的相邻关系,采用顺序存储结构的线性表通常称为顺序表。顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。
2.创建一个顺序表:
public class MyArrayList { private long[] array; private int size; public MyArrayList() { array = new long[2]; size = 0; Arrays.fill(array, Long.MIN_VALUE); }
3.对顺序表进行尾插操作:
public void add(long e) { ensureCapacity(); array[size] = e; size++; } private void ensureCapacity() { //对顺序表进行扩容 if (size < array.length) { return; } array = Arrays.copyOf(array, array.length * 2); Arrays.fill(array, size, array.length, Long.MIN_VALUE); }
4.对顺序表进行删除操作:
public void delete(int index) { //删除指定下标的元素 if (index < 0 || index >= size) { //判断下标是否合法 throw new ArrayIndexOutOfBoundsException(index + ": " + size); } for (int f = index + 1; f < size; f++) { int t = f - 1; array[t] = array[f]; } size--; array[size] = Long.MIN_VALUE; }
5.删除顺序表中指定的元素
public void removeFromHead(long e) { //删除指定元素 从前往后找 int index = 0; while (index < size) { if (array[index] == e) { break; } index++; } // 怎么区分是否找到 if (index == size) { // 没有找到 return; } for (int f = index + 1; f < size; f++) { int t = f - 1; array[t] = array[f]; } size--; array[size] = Long.MIN_VALUE; }
6.删除顺序表中所有指定的元素:
public void removeAll(long e) {//删除顺序表中所有的元素e long[] newarray = new long[array.length]; Arrays.fill(newarray,Long.MIN_VALUE); int to = 0; for(int from = 0; from < size; from++){ if(array[from] != e){ newarray[to] = array[from]; to++; } } array = newarray; size = to; }
7.返回指定元素的下标:
private int indexOf(long e){ // 返回元素的下标 for(int index = 0; index < size; index++){ if(array[index] == e) { return index; } } return -1; }
8.把元素插入到固定的位置:
public void add(int index, long e) { if (index < 0 || index > size) { throw new ArrayIndexOutOfBoundsException(index + ": " + size); } ensureCapacity(); for (int i = size - 1; i >= index; i--) { int j = i + 1; array[j] = array[i]; } array[index] = e; size++; }
如有错误,请指正。
下一篇:
排列组合的C语言实现