|
发表于 2023-10-31 22:56:24
|
显示全部楼层
本楼为最佳答案
 当我们需要实现一个循环列表时,可以使用链表的方式来实现。下面是一个用Java实现循环列表的示例代码,每行都有详细的注释解释:
- // 定义循环列表节点类
- class Node<T> {
- T data; // 节点数据
- Node<T> next; // 下一个节点的引用
- // 构造函数
- public Node(T data) {
- this.data = data;
- this.next = null;
- }
- }
- // 定义循环列表类
- class CircularList<T> {
- private Node<T> head; // 头节点
- // 构造函数
- public CircularList() {
- this.head = null;
- }
- // 添加节点到循环列表
- public void add(T data) {
- Node<T> newNode = new Node<>(data);
- // 如果列表为空,则将头节点指向新节点,并使新节点的next指向自身,形成循环
- if (head == null) {
- head = newNode;
- head.next = head;
- } else {
- // 找到最后一个节点
- Node<T> last = head;
- while (last.next != head) {
- last = last.next;
- }
- // 将最后一个节点的next指向新节点,并使新节点的next指向头节点
- last.next = newNode;
- newNode.next = head;
- }
- }
- // 遍历循环列表并打印节点数据
- public void print() {
- if (head == null) {
- System.out.println("循环列表为空");
- return;
- }
- Node<T> current = head;
- // 遍历循环列表,直到回到头节点
- do {
- System.out.println(current.data);
- current = current.next;
- } while (current != head);
- }
- }
- // 测试循环列表
- public class Main {
- public static void main(String[] args) {
- CircularList<Integer> circularList = new CircularList<>();
- // 添加节点到循环列表
- circularList.add(1);
- circularList.add(2);
- circularList.add(3);
- circularList.add(4);
- // 打印循环列表节点数据
- circularList.print();
- }
- }
复制代码
这段代码定义了一个循环列表类 CircularList ,其中包含了添加节点和打印节点的方法。在 main 函数中,我们创建了一个循环列表对象 circularList ,并添加了一些节点。最后,调用 print 方法打印循环列表中的节点数据。 |
|