package Linklist.DoubleListDemo;
/**
*
* 约瑟夫环问题java求解
* @Author: HML
* @Date: 2021/6/28 下午 7:17
* @Version 1.0
*/
public class Josephu {
public static void main(String[] args) {
CirCleLinkList list = new CirCleLinkList();
list.addCirCle(5);
list.list();
list.OutOfCircle(1,2,5);
}
}
//创建一个单向循环链表
class CirCleLinkList{
//创建一个first节点并初始化为空
private Boy first = null;
//添加小孩节点,构成一个循环单向链表
/**
* 添加元素到环形链表
* @param nums 传入的元素个数
*/
public void addCirCle(int nums){
if(nums < 1){
System.out.println("输入参数不合法");
return;
}
Boy curBoy = null;//创建辅助指针来构建环形链表
for (int i=1;i<=nums;i++){
//根据编号创建小孩节点
Boy boy = new Boy(i);
//判断如果是第一个节点
if(i == 1){
first = boy;//将当前元素赋值给first
first.setNext(first);//将first的下一个节点也指向自己(first),这里已经形成环了
//为进行后面元素的添加,我们需要一个辅助指针
curBoy = first;//让curboy同时也指向当前节点
}else {
curBoy.setNext(boy);//将当前节点的下一个节点指向要添加的节点
boy.setNext(first);//将添加节点的下一个指向第一个节点,形成环
curBoy = boy;//将curboy后移
}
}
}
//遍历当前循环链表
public void list(){
//判断链表是否为空
if (first == null){
System.out.println("链表空");
return;
}
//这里我们设置first不能动
Boy curBoy = first;
while (true){
System.out.printf("小孩的编号 %d\n",curBoy.getNo());
//是否遍历完毕,判断当前链表是否遍历完毕的条件:curBoy.getNext() == first
if (curBoy.getNext() == first){
System.out.println("遍历完毕");
break;
}
curBoy = curBoy.getNext();//curBoy后移
}
}
/**
* 出圈
* @param startNo :从第几个人开始出
* @param countNum :数几下
* @param nums :总人数
*/
public void OutOfCircle(int startNo,int countNum,int nums){
if (first == null || startNo < 1 || startNo >nums){
System.out.println("输入参数有误");
return;
}
//创建helper指针,帮助小孩出圈,这里helper指针是指向最后一个元素
Boy helper = first;//事先指向这个链表的最后一个节点,这里最后一个节点可以用first表示,因为是个环,最后一个节点元素总归还是要指向first
while (true){
if (helper.getNext() == first){
System.out.println("指向最后一个节点");
break;
}
helper = helper.getNext();//helper实现后移
}
//小孩报数前先让其确定位置,确定出圈的位置
for (int j=0;j<startNo - 1;j++){
first = first.getNext();
helper = helper.getNext();
}
//小孩报数时:first和helper同时移动,移动的的步长是根据countNum来确定的
//相当于取数据,也是一个循环操作
while (true){
if (helper == first){
System.out.println("圈中仅有一个节点");
System.out.printf("%d\n",first.getNo());
break;
}
//这里是根据要移动的数将first和helper移动相应的m-1次
for (int j=0;j<countNum - 1;j++){
first = first.getNext();
helper = helper.getNext();
}
//这时first指向的元素就是要出圈的元素
System.out.printf("小孩出圈%d\n",first.getNo());
//取出数据后讲表还要连起来,first实现后移,helper因为是在first之后,也就是标识最后一个节点,故此时,随着first的后移,
//helper也要后羿,后移也就是将first的值付给他
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后留在圈中的小孩%d\n",first.getNo());//这里使用first和helper均可,因为这里仅剩一个元素了
}
}
//创建一个boy类,表示一个节点
class Boy{
private int no;
private Boy next;
public Boy(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}
约瑟夫环----java实现学习
最新推荐文章于 2024-02-20 19:05:23 发布