约瑟夫环问题

问题描述

1 - n 个人围坐一圈,约定编号为k的人开始报数,数到m的那个人出列,直到所有人出列,由此产生一个队编号的序列

问题分析
  1. 先构造一个环形的单向链表
    1.首先创建一个Boy类存放next和val
    2.创建一个first指针指向第一个节点
    3.创建boy指针指向当前新创建的节点
    4.创建curBoy指针用来连接新节点
  2. 出链表
    1.判断开始孩子的编号n与总共孩子的个数
    2.用一个helper指针用来在删除节点的同时将链表重新环状
code
package com.lemon.josephu;

public class Josephu {
	private Boy boy = null;
	private Boy first = null;
	private Boy curBoy = null;
	
	//添加数据
	public void add(int num) {
		if(num < 1) {
			System.out.println("输入有误,添加失败℃");
			return ;
		}
		for(int i = 1; i <= num; i++) {
			boy = new Boy(i);
			if(i == 1) {
				first = boy;
				first.setNext(first);
				curBoy = first;
			}
			else {				
				curBoy.setNext(boy);
				boy.setNext(first);
				curBoy = boy;
			}
		}
		return ;
	}
	
	//显示数据
	public void show() {
		if(first == null) {
			System.out.println("环形链表中没有数据℃");
			return ;
		}
		System.out.println("孩子编号:" + first.getVal());
		Boy temp = first;
		while(temp.getNext() != first) {
			temp = temp.getNext();
			System.out.println("孩子编号:" + temp.getVal());
		}
		return ;
	}
	
	//依次输出
	public void countBoy(int n, int m, int sum) {
		if(sum < n) {
			System.out.println("输入有误~");
			return ;
		}
		if(first.getNext() == first) {
			System.out.printf("孩子的编号:%d\n", first.getVal());
			return ;
		}
		Boy helper = first;
		while(helper.getNext() != first) {
			helper = helper.getNext();
		}
		
		for(int i = 1; i < n; i++) {
			first = first.getNext();
			helper = helper.getNext();
		}
		while(first != first.getNext()) {
			for(int j = 1; j < m; j++) {
				first = first.getNext();
				helper = helper.getNext();
			}
			System.out.printf("孩子的编号:%d\n", first.getVal());
			first = first.getNext();
			helper.setNext(first);
		} 
		System.out.printf("孩子的编号:%d\n", first.getVal());
		return ;
	}
}


//Boy类
class Boy {
	private int val;
	private Boy next;
	
	public Boy(int val) {
		this.val = val;
	}

	public int getVal() {
		return val;
	}

	public void setVal(int val) {
		this.val = val;
	}

	public Boy getNext() {
		return next;
	}

	public void setNext(Boy next) {
		this.next = next;
	}
}```
```java
package com.lemon.josephu;

public class Test {
	public static void main(String[] args) {
		Josephu josephu = new Josephu();
		
		josephu.add(5);
		josephu.show();
		
		josephu.countBoy(2, 3, 5);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值