package LinkedList;
public class Josepfu {
public static void main(String[] args) {
CircleSingLinkedList circleSingLinkedList = new CircleSingLinkedList();
circleSingLinkedList.addBoy(5);
circleSingLinkedList.showBoy();
//测试一把小孩出圈是否正常
circleSingLinkedList.countBoy(1,2,5);
}
//创建一个环形的单向链表
public static class CircleSingLinkedList {
//创建一个first节点,当前没有编号
private Boy first = null;
//添加小孩节点,构建成一个环形的链表
public void addBoy(int nums) {
//nums 对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 = boy;
} else {
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;//辅助节点向后移动的意思
}
}
}
//遍历当前的环形链表
public void showBoy() {
if (first == null) {
System.out.println("没有任何小孩~~");
return;
}
//因为first不能动,所以还是要借助辅助节点
Boy curBoy = first;
while (true) {
System.out.println("小孩的编号为:" + curBoy.no);
if (curBoy.getNext() == first) {//说明整个链表已经遍历完成
break;
}
curBoy = curBoy.getNext();//curBoy向后移
}
}
//根据用户的输入,计算小孩出圈的顺序
//startNo 从哪开始 countNum 数几下出圈 nums最开始有多少人
public void countBoy(int startNo, int countNum, int nums) {
if (first == null || startNo < 1 || startNo > nums) {
System.out.println("参数输入有误请重新输入");
return;
}
Boy helper = first;
//需要创建一个辅助指针(变量)helper,实现指向环形链表的最后一个节点
while (true) {
if (helper.getNext() == first) {//一开始helper指向头 现在他的下一个next==头 则证明遍历完了
break;
}
helper = helper.getNext();
}
//当小孩报数时应该先让first和helper移动startNo-1次
for (int j = 0; j < startNo - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
//当小孩报数时,让first和helper指针同时移动countNum-1次,然后出圈
while (true){
if (helper==first){//说明圈中只有一个节点
break;
}
//让first和helper同时移动countNum-1
for (int j = 0; j < countNum-1; j++) {
first=first.getNext();
helper=helper.getNext();
}
//这是first指向的节点就是要出圈的最小节点
System.out.println("小孩"+first.getNo()+"出圈了");
//这时将first指向的小孩节点出圈
first=first.getNext();
helper.setNext(first);
}
System.out.println("最后留在圈中的小孩编号是"+first.getNo());
}
}
//创建一个Boy类,表示一个节点
public static class Boy {
private int no;//编号
private Boy next;//指向下一个节点,默认null
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-10-09 22:28:58 发布