顺序表
public class SequenceList<T> implements Iterable<T>{
private T[] eles;
private int N;
public SequenceList(int capacity){
eles = (T[]) new Object[capacity];
N = 0;
}
public void clear(){
N = 0;
}
public boolean isEmpty(){
return N == 0;
}
public int length(){
return N;
}
public T get(int i){
if (i < 0 || i >= N){
throw new RuntimeException("当前元素不存在");
}
return eles[i];
}
public void insert(T t){
if (N == eles.length){
throw new RuntimeException("线性表已满,添加失败");
}
eles[N] = t;
N++;
}
public void insert(int i,T t){
if (N == eles.length){
throw new RuntimeException("线性表已满,添加失败");
}
if (i < 0 || i > N){
throw new RuntimeException("添加元素的位置不合法");
}
for (int j = N; j > i ; j--) {
eles[j] = eles[j - 1];
}
eles[i] = t;
N++;
}
public T remove(int i){
if (N == 0){
throw new RuntimeException("线性表为空,删除失败");
}
if (i < 0 || i >= N){
throw new RuntimeException("删除元素的位置不合法");
}
T result = eles[i];
for (int j = i + 1; j < N; j++) {
eles[j - 1] = eles[j];
}
N--;
return result;
}
public int indexOf(T t){
if (N == 0){
throw new RuntimeException("线性表为空");
}
for (int i = 0; i < N; i++) {
if (eles[i].equals(t)){
return i;
}
}
return -1;
}
public void showEles(){
for (int i = 0; i < N; i++) {
System.out.println(eles[i]);
}
}
@Override
public Iterator<T> iterator() {
return new SIterator();
}
private class SIterator implements Iterator{
private int cur;
public SIterator(){
this.cur = 0;
}
@Override
public boolean hasNext() {
return cur < N;
}
@Override
public Object next() {
return eles[cur++];
}
}
public static void main(String[] args) {
SequenceList<String> s = new SequenceList<>(10);
s.insert("孙悟空");
s.insert("唐僧");
s.insert("猪八戒");
for (String s1 : s) {
System.out.println(s1);
}
System.out.println(s.get(1));
System.out.println(s.remove(2));
s.clear();
System.out.println(s.length());
}
}