什么是顺序表
顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元,依次存储线性表中的各个元素、使得线性表中再逻辑结构上响铃的数据元素存储在相邻的物理存储单元中,即通过数据元素物理存储的相邻关系来反映数据元素之间逻辑上的相邻关系;
常见的如数组:
在Java中顺序表一般体现为两种 数组 与 集合,数组是固定长度的顺序表,集合是动态长度的顺序表,这里实现动态长度的顺序表;
顺序表的实现(直接上代码)
public class SequenceListimplements Iterable { private T[] eles; private int N; private int modCount; public SequenceList(){ // this.eles =(T[]) new Object[1]; this.N = 0; } public void clear(){ modCount ++; for (int i = 0;i this.N){ System.out.println("异常"); return null; } return this.eles[index]; } public void insert(T t){ this.modCount++; ensureCapacityInternal(this.N+1); this.eles[this.N++] = t; } public void insert(int index,T t){ this.modCount++; if(index<0|| index>this.N){ System.out.println("异常"); return; } ensureCapacityInternal(this.N+1); for (int i = this.N; i>index; i--) { this.eles[i]= this.eles[i-1]; } this.eles[this.N++] = t; } public T remove(int index){ this.modCount++; if(index<=0|| index>this.N){ System.out.println("异常"); return null; } T t = eles[index]; for (int i = index; i this.eles.length){ num =this.eles.length; } System.arraycopy(this.eles,0,temp,0,num); this.eles = temp; } } public int indexOf(T t){ for (int i = 0; i < this.N; i++) { if(this.eles[i].equals(t)){ return i; } } return -1; } @Override public Iterator iterator() { return new MyIterator(); } private class MyIterator implements Iterator { private int cur ; private int num; public MyIterator(){ this.cur = 0; this.num = modCount; } @Override public boolean hasNext() { checkModCount(); return cur< N; } @Override public T next() { checkModCount(); return eles[cur++]; } private void checkModCount(){ if(this.num != modCount){ throw new RuntimeException("不合法的操作,在遍历元素时修改数据是不安全的!"); } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)