package Algorithm.Josepfu;
/**
* @author yangyiliy_liuyang
* 2022/11/19
* @version 1.0
* 约瑟夫环问题--单链表
*/
public class Main {
public static void main(String[] args) {
CorcleSingleLinkeList corcleSingleLinkeList = new CorcleSingleLinkeList();
corcleSingleLinkeList.addPeople(5);
corcleSingleLinkeList.showPeople();
corcleSingleLinkeList.countPeopple(2,1,5);
}
}
class CorcleSingleLinkeList {
private People firstPeople = null;
public void addPeople(int num) {
//num 增加学生的个数
//数据校验
if (num <= 0) {
return;
}
People curPeople = null;
for (int i = 1; i < num + 1; i++) {
//根据编号创建节点
People people = new People(i);
if (i == 1) {
firstPeople = people;
firstPeople.setNext(firstPeople);
curPeople = firstPeople;
} else {
curPeople.setNext(people);
people.setNext(firstPeople);
curPeople = people;
}
}
}
public void showPeople() {
if (firstPeople == null) {
return;
}
People curPeople = firstPeople;
while (true) {
System.out.println("no = " + curPeople.getNo());
if (curPeople.getNext() == firstPeople) {
break;
}
curPeople = curPeople.getNext();
}
}
/**
* @param start 从第几个人开始数数
* @param count 数多少下
* @param nums 最开始有多少人在圈中
*/
public void countPeopple(int start, int count, int nums) {
//校验
if (firstPeople == null || start < 1 || start > nums) {
return;
}
//1.创建一个helper指针,去遍历到环形单链表的最后一个节点位置,
// 然后first和helper都需要向后移动start-1下,方便开始从第几个人开始。
People helper = firstPeople;
while (true) {
if (helper.getNext() == firstPeople) {
break;
}
helper = helper.getNext();
}
for (int i = 0; i < start - 1; i++) {
firstPeople = firstPeople.getNext();
helper = helper.getNext();
}
//2.开始报数时,first和helper都需要向后移动count-1下
while (true) {
if (helper == firstPeople) {
break;
}
for (int i = 0; i < count - 1; i++) {
firstPeople = firstPeople.getNext();
helper = helper.getNext();
}
System.out.println("The one out of the circle is " + firstPeople.getNo());
//3.将first出圈
firstPeople = firstPeople.getNext();
helper.setNext(firstPeople);
}
System.out.println("Left behind is " + firstPeople.getNo());
}
}
class People {
private int no;
private People next;
People(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public People getNext() {
return next;
}
public void setNext(People next) {
this.next = next;
}
}
约瑟夫环问题
最新推荐文章于 2024-10-10 15:47:02 发布