问题如下(与分析)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/01c3abad78fb6a8144f12b3ffdafe884.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8d509a4eecba3d2df9a13e6d2a778547.png)
构建思路
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f483c424f6643bb3cdf275a1cc565476.png)
输入一个数,数到这个数的小孩出圈,出圈顺序的思路
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/17e77e5f45abeec411c03145a830230d.png)
代码实现
根据图解,来一步一步实现
public void countBoy(int startNo, int countNum, int nums){
if (first == null || startNo<1 || startNo > nums){
System.out.println("输入有误,重新输入");
return;
}
Boy helper = first;
while (true){
if (helper.getNext() == first){
break;
}
helper = helper.getNext();
}
for (int j = 0; j < startNo -1; j++){
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.printf("小孩 %d 出圈\n",first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.println("最后留在圈中的小孩编号:"+first.getNo());
}
}
测试
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.countBoy(1,2,5);
结果:
小孩 2 出圈
小孩 4 出圈
小孩 1 出圈
小孩 5 出圈
最后留在圈中的小孩编号:3
完整代码
package DataStructures.LinkedList;
public class Josepfu {
public static void main(String []args){
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.countBoy(1,2,5);
}
}
class CircleSingleLinkedList{
private Boy first = null;
public void showBoy(){
if (first == null){
System.out.println("链表为空");
return;
}
Boy cur = first;
while (true){
System.out.printf("小孩的编号是:%d \n",cur.getNo());
if (cur.getNext() == first){
break;
}
cur = cur.getNext();
}
}
public void addBoy(int nums){
if (nums<1){
System.out.println("nums的值不正确");
return;
}
Boy cur = null;
for (int i = 1; i <= nums; i++){
Boy boy = new Boy(i);
if (i == 1){
first = boy;
first.setNext(first);
cur = first;
} else {
cur.setNext(boy);
boy.setNext(first);
cur = boy;
}
}
}
public void countBoy(int startNo, int countNum, int nums){
if (first == null || startNo<1 || startNo > nums){
System.out.println("输入有误,重新输入");
return;
}
Boy helper = first;
while (true){
if (helper.getNext() == first){
break;
}
helper = helper.getNext();
}
for (int j = 0; j < startNo -1; j++){
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.printf("小孩 %d 出圈\n",first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.println("最后留在圈中的小孩编号:"+first.getNo());
}
}
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;
}
}