//判断是否为空
public boolean isEmpty() {
return this.first == null;
}
//添加。
public boolean add(T data) {
if (this.isEmpty()) {
this.addFirst(data);
} else {
Link temp = this.first;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Link(data);
ensureIndex();
}
return true;
}
//遍历
public void show() {
Link temp = this.first;
System.out.print("[");
while (temp != null) {
if (temp.next != null) {
System.out.print(temp.data + ",");
} else {
System.out.print(temp.data);
}
temp = temp.next;//this.first.next = current = new Link(23) != null
}
System.out.println("]");
}
//select from index
public T getByIndex(int index) {
Link temp = this.first;
for (int i = 0; i < index; i++) {
temp = temp.next;
if (temp == null) {
throw new IndexOutOfBoundsException("不正确的索引");
}
}
return (T) temp.data;
}
//修改元素:通过比较存储值是否equals,
public boolean replace(T data, T dataNew) {
Link temp = this.first;
while (true) {
if (temp == null) {
return false;
}
if (!(temp.data.equals(data))) {
temp = temp.next;
} else {
temp.data = dataNew;
return true;
}
}
}
//删除某个元素
public boolean remove(T data) {
if (this.first == null) {
return false;
}
Link temp = this.first;
if (temp.data.equals(data)) {
this.first = temp.next;
return true;
}
while (true) {
if (temp.next == null) {
return false;
}
if (!temp.next.data.equals(data)) {
temp = temp.next;
} else {
temp.next = temp.next.next;
ensureIndex();
}
}
}
//确定元素对应索引值。
private void ensureIndex() {
Link temp = this.first;
if (temp.index != 0) {
temp.index = 0;
}
while (temp.next != null) {
if (temp.next.index != temp.index + 1) {
temp.next.index = temp.index + 1;
temp = temp.next;
} else {
temp = temp.next;
}
}
}
private class Link<T> {
public T data;
public Link next;
public Link first;