package com.atguigu.linkedlist;
public class Josephu {
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("nums不正确");
return;
}
Boy curBoy=null;//辅助创建环形链表
//使用for循环创建环形链表
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 showBoy(){
if(first==null){
System.out.println("链表为空");
return;
}
Boy curBoy=first;
while (true){
System.out.println(curBoy.getNo());
if(curBoy.getNext()==first){
break;
}
curBoy=curBoy.getNext();
}
}
//根据用户输入,计算出圈顺序
/**
*
* @param startNo 从第几个节点开始
* @param countNum 数几下出圈
* @param nums 最初有多少个节点
*/
public void countBoy(int startNo,int countNum,int nums){
if(first==null||startNo<1||startNo>nums){
System.out.println("参数有误");
}
Boy helper=first;
while (true){
if(helper.getNext()==first){
break;
}
helper=helper.getNext();
}
//报数前先移动到指定位置
for(int i=0;i<startNo-1;i++){
first=first.getNext();
helper=helper.getNext();
}
//开始出圈,知道只剩一个节点
while (true){
if(helper==first){
break;
}
//移动指定次数
for (int i = 0; i < countNum - 1; i++) {
first=first.getNext();
helper=helper.getNext();
}
System.out.println(first.getNo());
//first出圈
first=first.getNext();
helper.setNext(first);
}
System.out.println(helper.getNo());
}
}
//创建一个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;
}
}
单向环形链表实现约瑟夫问题
最新推荐文章于 2024-05-20 22:31:31 发布