java实现顺序表的构建、插入、删除、查找、反转及测试代码
时间: 2023-09-19 12:06:14 浏览: 98
顺序表是一种线性表,它的元素存储在连续的内存空间中。下面是Java实现顺序表的构建、插入、删除、查找、反转及测试代码:
```java
public class MyArrayList<T> {
private Object[] elements;
private int size;
public MyArrayList() {
this.elements = new Object[10];
this.size = 0;
}
public void add(T element) {
if (size == elements.length) {
resize();
}
elements[size++] = element;
}
private void resize() {
Object[] newElements = new Object[size * 2];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
public void insert(int index, T element) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
if (size == elements.length) {
resize();
}
System.arraycopy(elements, index, elements, index + 1, size - index);
elements[index] = element;
size++;
}
public void delete(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
System.arraycopy(elements, index + 1, elements, index, size - index - 1);
elements[size - 1] = null;
size--;
}
public int find(T element) {
for (int i = 0; i < size; i++) {
if (elements[i].equals(element)) {
return i;
}
}
return -1;
}
public void reverse() {
for (int i = 0, j = size - 1; i < j; i++, j--) {
Object temp = elements[i];
elements[i] = elements[j];
elements[j] = temp;
}
}
public static void main(String[] args) {
MyArrayList<Integer> list = new MyArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
System.out.println("Before insert:");
for (int i = 0; i < list.size; i++) {
System.out.print(list.elements[i] + " ");
}
System.out.println();
list.insert(2, 6);
System.out.println("After insert:");
for (int i = 0; i < list.size; i++) {
System.out.print(list.elements[i] + " ");
}
System.out.println();
list.delete(3);
System.out.println("After delete:");
for (int i = 0; i < list.size; i++) {
System.out.print(list.elements[i] + " ");
}
System.out.println();
int index = list.find(4);
System.out.println("Index of 4: " + index);
list.reverse();
System.out.println("After reverse:");
for (int i = 0; i < list.size; i++) {
System.out.print(list.elements[i] + " ");
}
System.out.println();
}
}
```
运行结果如下:
```
Before insert:
1 2 3 4 5
After insert:
1 2 6 3 4 5
After delete:
1 2 6 4 5
Index of 4: 3
After reverse:
5 4 6 2 1
```
阅读全文