約瑟夫問題java代碼
curBoy爲輔助節點
我測試的是5個人的,最終答案是24153。
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList cs = new CircleSingleLinkedList();
cs.addBoy(5);
cs.list();
//測試小孩出圈是否成功
cs.countBoy(1, 2, 5);
}
}
class CircleSingleLinkedList{
private Boy first = null;
public void addBoy(Integer 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.setNext(first);
curBoy = first;
}else {
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;
}
}
}
//遍歷當前環形鏈表
public void list(){
//判斷是否爲空
if (first == null){
System.out.println("鏈表爲空");
return;
}
//因爲first不能動,因此我們仍需要一個輔助指針
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;
while (true){
if (helper.getNext() == first){
break;
}
helper = helper.getNext();
}
//小孩報數前先讓first和helper移動k - 1次
for (int j = 0; j < startNo - 1; j++){
first = first.getNext();
helper = helper.getNext();
}
//當小孩報數時,helper和first同時移動m-1次
while (true){
//說明圈中只有一個節點
if (helper == first){
break;
}
//讓first和helper同時移動countNum-1
for (int j = 0; j < countNums - 1; j++){
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩%d出圈\n", first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最後留在圈中的小孩是%d", first.getNo());
}
}
class Boy{
private Integer no;
private Boy next;
public Boy(Integer no){
this.no = no;
}
public Integer getNo() {
return no;
}
public Boy getNext() {
return next;
}
public void setNo(Integer no) {
this.no = no;
}
public void setNext(Boy next) {
this.next = next;
}
@Override
public String toString() {
return "Boy{" +
"no=" + no +
", next=" + next +
'}';
}
}
運行結果