1、基本介绍
2、应用实例
package linkedlist;
public class Josephu {
public static void main(String[] args) {
SingleCircleLinkedList circleLinkedList = new SingleCircleLinkedList();
circleLinkedList.createCircleLinkedList(5);
circleLinkedList.traverseCircleLinkedList();
circleLinkedList.countCircleLinkedList(5, 1, 2); // 从自身开始数
}
}
class SingleCircleLinkedList {
private Node first = null;
// 构建环形链表
public void createCircleLinkedList(int num) {
if (num < 1) {
System.out.println("玩不了~");
return;
}
Node curr = null;
for (int i = 1; i <= num; i++) {
Node node = new Node(i);
if (i == 1) { // 创建第一个节点时,让first指向第一个节点
first = node;
node.next = first;
curr = node;
} else {
curr.next = node;
node.next = first;
curr = node;
}
}
}
// 遍历环形链表
public void traverseCircleLinkedList() {
if (first == null) {
System.out.println("游戏无法开始~");
return;
}
// 确保最后一个节点的值也能输出来
System.out.print("遍历单向环形链表:");
Node temp = first;
do {
System.out.print(temp.data + " ");
temp = temp.next;
} while (temp != first);
System.out.println();
}
// 小孩出圈
public void countCircleLinkedList(int allNodes, int startNode, int count) {
if (first == null || allNodes < 1 || startNode > allNodes) {
System.out.println("该游戏玩不了~");
return;
}
// 因为要删除节点,所以要借用一个辅助指针,指向被删除节点的前一个节点
Node helper = first; // 指向环形链表的最后一个节点
while (helper.next != first) {
helper = helper.next;
}
// 报数前,让 first 和 helper 同时移动 startNode - 1次,指向开始报数的节点
for (int i = 0; i < startNode - 1; i++) {
first = first.next;
helper = helper.next;
}
// 通过循环不断地将环形链表中的节点出圈
while (true) {
// 只剩一个节点时退出循环
if (helper == first){
System.out.println("出圈节点:" + first.data); // 将最后一个节点的值输出
break;
}
// 数count - 1次,将first指向要出圈的节点
for (int i = 0; i < count - 1; i++) {
first = first.next;
helper = helper.next;
}
// 将first指向的节点出圈
System.out.println("出圈节点:" + first.data);
first = first.next;
helper.next = first;
}
}
}
// 节点类
class Node{
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}