java顺序表就地逆置
时间: 2023-10-14 16:21:22 浏览: 125
以下是Java顺序表就地逆置的示例代码:
```java
public class SeqListReverse {
public static void main(String[] args) {
SeqList list = new SeqList();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.insert(5);
System.out.println("原始顺序表:" + list.toString());
reverse(list);
System.out.println("逆置后顺序表:" + list.toString());
}
public static void reverse(SeqList list) {
int length = list.size();
for (int i = 0; i < length / 2; i++) {
int temp = list.get(i);
list.set(i, list.get(length - i - 1));
list.set(length - i - 1, temp);
}
}
}
class SeqList {
private int[] array;
private int size;
public SeqList() {
array = new int[10];
size = 0;
}
public void insert(int value) {
if (size >= array.length) {
int[] newArray = new int[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
array[size++] = value;
}
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return array[index];
}
public void set(int index, int value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
array[index] = value;
}
public int size() {
return size;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(array[i]);
if (i != size - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
```
运行结果:
```
原始顺序表:[1, 2, 3, 4, 5]
逆置后顺序表:[5, 4, 3, 2, 1]
```
阅读全文