java不用链表怎么编写一个类似链表的程序
时间: 2023-11-24 21:07:39 浏览: 42
Java中可以使用数组来模拟链表的数据结构,具体实现方法如下:
1. 定义节点类Node,包含数据元素和指向下一个节点的索引
```
public class Node {
private int data;
private int next; // 指向下一个节点的索引
public Node(int data, int next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
}
```
2. 定义链表类LinkedList,包含一个Node类型数组和一个指向头节点的索引
```
public class LinkedList {
private Node[] nodes;
private int head; // 指向头节点的索引
public LinkedList(int size) {
nodes = new Node[size];
for (int i = 0; i < size; i++) {
nodes[i] = new Node(0, i + 1); // 初始化每个节点的数据元素为0,指向下一个节点的索引为下一个数组下标
}
nodes[size - 1].setNext(-1); // 最后一个节点的指向下一个节点的索引为-1,表示链表结尾
head = 0; // 头节点的索引为0
}
public void add(int data) {
int index = head; // 从头节点开始查找
while (nodes[index].getNext() != -1) { // 如果当前节点不是链表结尾
index = nodes[index].getNext(); // 指向下一个节点
}
nodes[index].setData(data); // 将数据元素存入当前节点
int newIndex = nodes[index].getNext(); // 获取空闲节点的索引
if (newIndex != -1) { // 如果还有空闲节点
nodes[index].setNext(newIndex); // 当前节点指向空闲节点
head = newIndex; // 头节点更新为空闲节点
nodes[newIndex].setNext(-1); // 将空闲节点的指向下一个节点的索引设置为-1,表示链表结尾
}
}
public void printList() {
int index = head; // 从头节点开始遍历
while (index != -1) { // 如果当前节点不是链表结尾
System.out.print(nodes[index].getData() + " "); // 输出当前节点的数据元素
index = nodes[index].getNext(); // 指向下一个节点
}
System.out.println();
}
}
```
3. 在主函数中进行测试
```
public static void main(String[] args) {
LinkedList list = new LinkedList(10); // 创建链表对象
list.add(1);
list.add(2);
list.add(3);
list.printList(); // 输出链表元素
}
```
输出结果为:1 2 3
以上就是使用数组模拟链表的实现方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)