public class CircleSingleLinkedList {
//创建第一个first节点,当前无编号
private Node first = null;
//添加小孩节点,构成一个环形链表
public void addBoy(int nums) {
//判断nums是否是负数
if (nums < 1) {
System.out.println("输入值不正确!");
return;
}
//辅助变量
Node curBoy = null;
//使用for循环来创建单向循环链表
for (int i = 1; i <= nums; i++) {
//根据编号来创建小孩
Node boy = new Node(i);
//如果是第一个小孩
if (i == 1) {
first = boy; //固定first
first.setNext(first); //构成环
curBoy = first;
} else {
curBoy.setNext(boy); //连接下一个节点
boy.setNext(first); //构成闭环
curBoy = boy; //让辅助变量改变为现在的节点
}
}
}
//遍历单向循环链表
public void showBoy() {
//判断链表是否为空
if (first == null) {
System.out.println("没有任何小孩!");
}
//辅助变量,因为first不能动
Node curBoy = first;
//循环开始
while (true) {
System.out.printf("小孩的编号%d\n", curBoy.getNo());
if (curBoy.getNext() == first) {
System.out.println("链表遍历完毕!");
break;
}
curBoy = curBoy.getNext(); //辅助变量后移
}
}
/**
*
* @param startBoy-选的那个小孩开始数数
* @param countNum-数几下小孩
* @param nums-创建小孩的个数
*/
//根据用户的输入选小孩
public void countBoy(int startBoy, int countNum, int nums) {
//先对输入的数据进行检验
if (first == null || startBoy < 1 || startBoy > nums) {
System.out.println("参数输入有误");
return;
}
//创建一个辅助指针,帮助小孩出圈
Node helper = first;
//让辅助变量指向单向环形链表的最后一个节点
while (true) {
if (helper.getNext() == first) {
//说明已经指到最后一个节点
break;
}
helper = helper.getNext();
}
//小孩报数前,先让helper和first移动k-1次
for (int i = 0; i < startBoy - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
//当小孩报数时,将helper和first移动m-1次
//这里是一个循环操作,直到圈中只有一个节点
while (true) {
if (helper == first) {
//说明圈中只有一个节点
break;
}
//当小孩报数时,将helper和first移动countNum - 1次
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
//first指的节点就是小孩出圈的节点
System.out.printf("小孩%d出圈\n", first.getNo());
//这是将first指向的小孩出圈
// first是移动指针 get
// helper是路径指针 set
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后留在圈中的小孩的编号是: %d",first.getNo());
}
}
class Josepfu {
public static void main(String[] args) {
//创建一个单向循环链表
CircleSingleLinkedList csll = new CircleSingleLinkedList();
//添加小孩个数
csll.addBoy(5);
//遍历小孩链表
csll.showBoy();
//小孩出圈的
csll.countBoy(1,2,5);
}
}
class Node {
private int no;
private Node next;
//构造器
public Node(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Java数据结构 | 单向环形链表--约瑟夫问题的代码实现
最新推荐文章于 2024-06-08 09:56:07 发布