思路
package linkedlist;
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.add(5);
circleSingleLinkedList.showBoy();
circleSingleLinkedList.countBoy(1,2,5);
}
}
class CircleSingleLinkedList{
//创建一个first结点,当前没有编号
private Boy first = null;
// 添加小孩节点,构建成一个环形的链表
public void add(int nums){
if(nums < 1){
System.out.println("nums的值不正确");//2 2->4->1->5->3
return;
}
// 辅助指针,帮助构建环形链表
//first不能移动,需要辅助指针指向当前添加的结点
Boy curBoy = null;
for(int i = 1;i <= nums;i++){
// 根据编号,创建小孩节点 新添加的结点
Boy boy = new Boy(i);
if(i == 1){//?????为什么单独写出来
/*因为只有一个结点的情况下,curBoy.setNext是空的,
会发生空指针异常*/
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;
}
// 因为first不能动,因此我们仍然使用一个辅助指针完成遍历
Boy curBoy = first;
while(true){
System.out.printf("小孩的编号%d\n",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("参数输入错误,请重新输入");
return;
}
// 创建要给辅助指针,帮助完成小孩出圈
Boy helper = first;
//需要创建一个赋值变量helper,事先指向环形链表的最后这个结点
while (true){
if(helper.getNext() == first){//说明指向first指向的小孩结点的前一位
break;
}
helper = helper.getNext();
}
//小孩报数前,先让first指向开始报数小孩的结点,同样helper也跟随移动
//这里计数的是移动的次数,不是一共转移了多少步
for(int j = 0; j < startNo - 1; j++){
first = first.getNext();
helper = helper.getNext();
}
//当小孩报数时,让first 和 helper 指针同时 的移动 m - 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();
}
System.out.printf("小孩%d出圈\n",first.getNo());
//这时将first指向的小孩节点出圈
first = first.getNext();//指向出圈小孩的下一个
helper.setNext(first);
}
System.out.printf("最后留在圈中的小孩编号%d\n",first.getNo());
}
}
class Boy{
private int no;
private Boy next;
public Boy(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public Boy getNext() {
return next;
}
public void setNo(int no) {
this.no = no;
}
public void setNext(Boy next) {
this.next = next;
}
}