package com.xkp.data.LinkerList;
/**
* @author xkp
* @version 1.0
* @className Josepfu
* @description 单向环形链表处理约瑟夫问题
* @date 2020/11/30 0030 23:12
**/
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.showBoy();
circleSingleLinkedList.countBoy(1,2,5);
}
}
class CircleSingleLinkedList {
private Boy first = new Boy(-1);
/**
* 添加小孩节点,形成环形链表
*/
public void addBoy(int nums) {
if (nums < 1) {
System.out.println("num值不正确");
return;
}
//辅助指针
Boy curBoy = null;
for (int i = 1; i <= nums; i++) {
//根据编号,创建小孩节点
Boy boy = new Boy(i);
//如果是第一个小孩
if (i == 1) {
first = boy;
//构成环状链表
first.setNext(first);
//curBoy指向第一个小孩
curBoy = first;
} else {
//1.新增时,首先cur.next指向新增节点
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;
}
}
}
/**
* 显示boy
*/
public void showBoy() {
if (first == null) {
System.out.println("没有任何小孩");
return;
}
Boy curBoy = first;
while (true) {
System.out.printf("小孩的编号 %d \n", curBoy.getNo());
if (curBoy.getNext() == first) {
//遍历完毕
break;
}
//当前指针后移
curBoy = curBoy.getNext();
}
}
/**
* 根据用户输入,计算出小孩出圈序列
*
* @param startNo 表示从第几个小孩开始数数
* @param countNums 表示数几下
* @param nums 表示小孩总数
*/
public void countBoy(int startNo, int countNums, int nums) {
if (first == null || startNo < 1 || startNo > nums) {
System.out.println("参数输入有误,请重新输入");
return;
}
Boy helper = first;
//首先使helper指向最后节点
while (true) {
if (helper.getNext() == first) {
break;
}
helper = helper.getNext();
}
//小孩报数前先让first和helper移动startNo-1次
for (int j = 0; j < startNo - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
//当小孩报数时,让first和 helper移动m-1次,然后出圈
//循环直到圈中只有一个人(helper==first)
while (true) {
if (helper == first) {
break;
}
for (int i = 0; i < countNums - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩%d出圈\n", first.getNo());
//这时将first指向的小孩出圈
first=first.getNext();
helper.setNext(first);//
}
System.out.printf("最后留在圈中的小孩%d出圈\n",helper.getNo());
}
}
class Boy {
private int no;
private Boy next;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}
单向环形链表解决约瑟夫问题
最新推荐文章于 2024-07-22 14:15:06 发布