java的单向循环链表
时间: 2023-11-13 18:55:43 浏览: 97
单向循环链表
Java的单向循环链表是一种数据结构,它与单向链表类似,但是最后一个节点指向头节点,形成一个环。这种数据结构可以用于需要循环遍历的场景,比如游戏中的角色移动。
下面是Java实现单向循环链表的示例代码:
```
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public class CircularLinkedList {
Node head;
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
head.next = head;
} else {
Node current = head;
while (current.next != head) {
current = current.next;
}
current.next = newNode;
newNode.next = head;
}
}
public void print() {
if (head == null) {
System.out.println("List is empty");
} else {
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
}
```
阅读全文