SeqList(顺序表)
代码部分:
public class SeqList<T> {
protected Object[] element;//声明一个对象数组
protected int len;//声明一个顺序表长度,记载实际元素个数
//构造函数1,固定长度
public SeqList(int size) {
this.element = new Object[size];
this.len = 0;
}
//构造函数2,默认长度,构造方法重载
public SeqList() {
this(64);
}
//构造函数3,由values数组提供元素
public SeqList(T[] values) {
this(values.length);
for (int i = 0; i < values.length; i++) {
this.element[i] = values[i];
}
this.len = element.length;
}
public boolean isEmpty() {
return this.len == 0;
}
public int length() {
return len;
}
public T get(int i) {
return i >= 0 && i < this.len ? (T) this.element[i] : null;
}
public void set(int i, T x) {
if (x == null) {
throw new NullPointerException("x==null");
} else if (i >= 0 && i < this.len) {
this.element[i] = x;
} else {
throw new IndexOutOfBoundsException(String.valueOf(i));
}
}
public int insert(int i, T x) {
if (x == null) {
throw new NullPointerException("x==null");
} else {
if (i < 0) {
i = 0;
}
if (i > this.len) {
i = this.len;
}
Object[] source = this.element;
int j;
if (this.len == this.element.length) {
this.element = new Object[source.length * 2];
for (j = 0; j < i; ++j) {
this.element[j] = source[j];
}
}
for (j = this.len - 1; j >= i; --j) {
this.element[j + 1] = source[j];
}
this.element[i] = x;
++this.len;
return i;
}
}
public int insert(T x) {
return this.insert(this.len, x);
}
public T remove(int i) {
if (this.len > 0 && i >= 0 && i < this.len) {
T old = (T) this.element[i];
for (int j = i; j < this.len - 1; ++j) {
this.element[j] = this.element[j + 1];
}
this.element[this.len - 1] = null;
--this.len;
return old;
} else {
return null;
}
}
public void removeAll() {
this.len = 0;
}
public int search(T key) {
for (int i = 0; i < this.len; ++i) {
if (key.equals(this.element[i])) {
return i + 1;
}
}
return -1;
}
protected void look() {
if (element != null) {
System.out.println("");
for (int i = 0; i < element.length; i++) {
System.out.print(" " + element[i]);
}
}
}
}
写在最后:
仅为学习阶段记录写过的代码,方便自己查找,初出茅庐,有不完善的地方烦请指正,如有继承类可查阅数据结构其他博文。