package com.pro.linkedlist;
public class Boy {
//创建一个Boy类
private int no;//编号
private Boy next;//指向下一个指针的节点,默认null
public Boy(int no) {
super();
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;
}
}
package com.pro.linkedlist;
public class JosepfuCircleSingleLinkedList {
// 创建一个当前没有编号的first节点
private Boy first = null;
public void addBoy(int nums) {
// 对nums进行数据校验
if (nums < 1) {
System.out.println("nums的值不正确");
return;
}
// 使用for来创建我们的环形链表
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;// 让curBoy指向第一个小孩
}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.getNo());
if(curBoy.getNext()==first){
break;
}
curBoy=curBoy.getNext();//curBoy后移
}
}
//根据用户输入,计算小孩出圈的顺序
/**
* @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("参数输入有误,请重新输入");
return;
}
//创建一个辅助变量,帮助完成这个小孩出圈
Boy helper=first;
//helper事先应该指向环形链表的最后这个节点
while (true) {
if(helper.getNext()==first){
break;//说明helper指向小孩的最后一个节点
}
helper=helper.getNext();
}
//小孩报数前,先让first和helper移动k-1次,
for (int i = 0; i < startNo-1; i++) {
first=first.getNext();
helper=helper.getNext();
}
//当小孩报数时,让first和helper指针同时移动m-1次,然后出圈
//循环此操作,知道剩最后一个节点
while (true) {
if(helper==first)
{
break;
}else {
//让first和helper指针同时移动countNum-1
for (int i = 0; i < countNum-1; i++) {
first=first.getNext();
helper=helper.getNext();
}
//此时first指向的节点,就是要出圈的小孩的节点
System.out.println("小孩"+first.getNo()+"出圈");
//这时将first指向的哪个小孩节点出圈
first=first.getNext();
helper.setNext(first);
}
System.out.println("最后留在圈中的小孩编号为:"+helper.getNo());
}
}
}
package com.pro.linkedlist;
public class Josepfu {
public static void main(String[] args) {
JosepfuCircleSingleLinkedList josepfuCircleSingleLinkedList = new JosepfuCircleSingleLinkedList();
josepfuCircleSingleLinkedList.addBoy(5);//加入5个小孩
josepfuCircleSingleLinkedList.showBoy();
josepfuCircleSingleLinkedList.countBoy(1,2,5);
}
}