public class Demo {
public static void main(String[] args) {
CirccleSingleLinkList linkList=new CirccleSingleLinkList();
linkList.add(10);
// linkList.list();
linkList.show(1,3,10);
}
}
class CirccleSingleLinkList{
//创建一个first节点
private Boy firstBoy=null;
//添加小孩
public void add(int nums){
//判nums是否是合法数据
if(nums<1){
return;
}
//创建辅助节点,头节点不能动
Boy curBoy=null;
//创建环形
for (int i = 1; i <= nums; i++) {
//创建boy
Boy boy =new Boy(i);
//如果是第一个节点,形成闭环
if(i==1){
//头结点指向第一个小孩
firstBoy=boy;
//形成闭环
firstBoy.setNext(firstBoy);
//给辅助节点赋值
curBoy=firstBoy;
}else {
//当前节点指向下一节点
curBoy.setNext(boy);
//被指向的节点指向头结点
boy.setNext(firstBoy);
//辅助指针后移一位
curBoy=boy;
}
}
}
public void list(){
if(firstBoy==null){
System.out.println("链表为空");
return;
}
//创建辅助节点
Boy curBoy=firstBoy;
while (true) {
//打印输出编号
System.out.println("小孩的编号"+curBoy.getNo());
//判断下一个节点是否指向头结点
if (curBoy.getNext() == firstBoy){
break;
}
//后移
curBoy=curBoy.getNext();
}
}
//出圈
/**
*
* @param m 从哪一个编号开始
* @param k 计数多少下
* @param sums 总人数
*/
public void show(int m,int k,int sums){
if(firstBoy==null||m>sums||k<1){
System.out.println("数据不合法");
}
//创建辅助节点
Boy last=firstBoy;
while (true) {
//说明尾节点指向头结点
if (last.getNext() ==firstBoy ) {
break;
}
//后移
last = last.getNext();
}
//移动到m编号
for (int i = 0; i <m-1 ; i++) {
//头指针往下移
firstBoy=firstBoy.getNext();
//尾指针也往下移
last=last.getNext();
}
//循环所有节点
while (true){
// 最后一个节点
if(last==firstBoy){
break;
}
for (int j = 0; j <k-1 ; j++) {
//头指针往下移
firstBoy=firstBoy.getNext();
//尾指针也往下移
last=last.getNext();
}
System.out.println("小孩出圈的顺序"+firstBoy.getNo());
//要出圈的节点指向下一个节点
firstBoy=firstBoy.getNext();
//要出圈的上一个节点指向要出圈的节点的下一个节点
last.setNext(firstBoy);
}
//剩下最后一个节点
System.out.println("最后小孩编号"+last.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;
}
@Override
public String toString() {
return "Boy{" +
"no=" + no +
", next=" + next +
'}';
}