顺序表的建立查找与删除代码
时间: 2023-12-27 17:19:46 浏览: 17
顺序表的建立:
```java
public class SeqList {
private int[] data; // 数据存储数组
private int size; // 当前元素个数
private int capacity; // 最大容量
public SeqList(int capacity) {
this.data = new int[capacity];
this.size = 0;
this.capacity = capacity;
}
public int getSize() {
return size;
}
public int getCapacity() {
return capacity;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public void insert(int index, int value) {
if (isFull()) {
throw new RuntimeException("SeqList is full");
}
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index out of range");
}
for (int i = size - 1; i >= index; i--) {
data[i + 1] = data[i];
}
data[index] = value;
size++;
}
public void delete(int index) {
if (isEmpty()) {
throw new RuntimeException("SeqList is empty");
}
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of range");
}
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
}
public int search(int value) {
for (int i = 0; i < size; i++) {
if (data[i] == value) {
return i;
}
}
return -1;
}
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of range");
}
return data[index];
}
public void set(int index, int value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of range");
}
data[index] = value;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(data[i]);
if (i != size - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
```
顺序表的查找:
```java
public int search(SeqList seqList, int value) {
for (int i = 0; i < seqList.getSize(); i++) {
if (seqList.get(i) == value) {
return i;
}
}
return -1;
}
```
顺序表的删除:
```java
public boolean delete(SeqList seqList, int value) {
int index = search(seqList, value);
if (index == -1) {
return false;
}
seqList.delete(index);
return true;
}
```