java实现环形链表
时间: 2024-03-22 08:35:09 浏览: 23
Java可以通过定义一个Node类和一个CircularLinkedList类来实现环形链表。Node类表示链表中的节点,包含一个数据域和一个指向下一个节点的指针。CircularLinkedList类则包含一个指向链表头节点的指针,并提供了一些操作方法来实现环形链表的功能。
下面是一个简单的Java代码示例:
```java
// 定义节点类
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
// 定义环形链表类
class CircularLinkedList {
Node head;
public CircularLinkedList() {
this.head = null;
}
// 在链表末尾插入节点
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
head.next = head; // 将头节点的next指针指向自己,形成环
} else {
Node temp = head;
while (temp.next != head) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = head;
}
}
// 遍历并打印链表
public void display() {
if (head == null) {
System.out.println("链表为空");
return;
}
Node temp = head;
do {
System.out.print(temp.data + " ");
temp = temp.next;
} while (temp != head);
System.out.println();
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
list.display(); // 输出:1 2 3
}
}
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)