day4学习
package LinkedList;
public class josepfu {
public static void main(String[] args) {
//测试构建环形列表和遍历是否正确
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.showBoy();
//测试小孩出圈是否正确
circleSingleLinkedList.countBoy(1, 2, 5);
}
}
//创建一个环形单向列表
class CircleSingleLinkedList {
//创建一个first节点 当前没有编号
private Boy first = new Boy(-1);
//添加boy节点 构成链表
public void addBoy(int nums) {
//对于nums做一个简单的数据校验
if(nums < 1) {
System.out.println("数量不正确");
return;
}
Boy curBoy = null;//辅助指针,帮助构建环形表
for (int i = 1; i <= nums; i++) {
//根据编号创建Boy节点
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.printf("小孩的编号%d \n",curBoy.getNo());
if(curBoy.getNext() == first) {//说明已经遍历完毕
break;
}
curBoy = curBoy.getNext();
}
}
/*
* 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只想了最后节点
break;
}
helper = helper.getNext();
}
//小孩报数前 先让first 和 helper移动到对应开始的节点
for (int j = 0; j < startNo - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
//移动m-1次 开始出圈
//这是一个循环操作直到圈里面只有一个节点
while(true) {
if(helper == first) {//说明圈中只有一人
break;
}
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}//这时first指向小孩就是要出圈的小孩
System.out.printf("小孩%d出圈\n",first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后留在圈中的小孩是%d \n",helper.getNo());
}
}
//创建一个Boy类表示一个节点
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;
}
}