写一段用数组的链表代码
时间: 2023-05-25 22:04:54 浏览: 62
这里是使用数组实现链表的示例代码:
```java
public class ArrayLinkedList {
private int[] array; // 数组
private int size; // 链表的长度,初始为0
// 构造方法
public ArrayLinkedList() {
array = new int[10];
size = 0;
}
// 在链表末尾添加元素
public void add(int value) {
if (size == array.length) {
int[] newArray = new int[size + 10];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
array[size++] = value;
}
// 获取链表指定位置的元素
public int get(int index) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
return array[index];
}
// 获取链表长度
public int getSize() {
return size;
}
// 在链表指定位置添加元素
public void add(int index, int value) {
if (index > size || index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
if (size == array.length) {
int[] newArray = new int[size + 10];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
System.arraycopy(array, index, array, index + 1, size - index);
array[index] = value;
size++;
}
// 从链表中删除指定位置的元素
public void remove(int index) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
System.arraycopy(array, index + 1, array, index, size - index - 1);
size--;
}
}
```
这个数组实现的链表中,每个节点都是数组的一个元素,节点的值即为元素的值。使用数组实现链表的好处是可以节省空间,只需要存储节点的值,不需要存储指向下一个节点的指针。缺点是插入和删除操作的效率较低,因为需要移动数组中的元素。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)