package CLLList;
/**
@author xgz
@date 创建时间:2019年7月31日 上午10:53:02
@version 1.0
*/
public class Josephu extends CLinkList{
public static void main(String[] args) {
CLinkList linkList = new CLinkList();
CLLNode headNode = null;
CLLNode temp1 = new CLLNode(12);
CLLNode temp2 = new CLLNode(13);
CLLNode temp3 = new CLLNode(14);
CLLNode temp4 = new CLLNode(15);
CLLNode temp5 = new CLLNode(16);
CLLNode temp6 = new CLLNode(17);
headNode = linkList.InsertAtEndInCLL(headNode, temp1);
headNode = linkList.InsertAtEndInCLL(headNode, temp2);
headNode = linkList.InsertAtEndInCLL(headNode, temp3);
headNode = linkList.InsertAtEndInCLL(headNode, temp4);
headNode = linkList.InsertAtEndInCLL(headNode, temp5);
headNode = linkList.InsertAtEndInCLL(headNode, temp6);
// linkList.DelectNodeFromCLL(headNode, temp5);
linkList.Printl(headNode);
System.out.println(linkList.GetListLength(headNode));
show(headNode,6,1,2);
}
/**
*
@Description:
@parameter int sum 环内有多少小孩,int start 从哪个小孩开始报数 ,
int count 数到几出局
@return 返回值
@throws 异常类及抛出条件
*/
static void show(CLLNode headNode,int sum,int start ,int count) {
//校验
CLLNode first = headNode ;
CLLNode helper = headNode ;
if(first == null || start > sum || start < 1) {
System.out.println("参数有误");
return;
}
//创建辅助指针helper,并让其指向链表的最后一个节点 即temp6
while(true) {
if(helper.getNext() == first) {
break;
}
helper = helper.getNext();
}
//小孩报数前,让first和helper移动 start - 1 次
for(int j = 0; j < start -1; j ++) {
first = first.getNext();
helper = helper.getNext();
}
//小孩报数时,让first和helper移动 count- 1 次
//循环,直到圈里只有一个小孩
System.out.println("要出圈的小孩:" );
while(true) {
if(helper == first) {
break;
}
//让first和helper移动 count- 1 次
for(int j = 0; j < count -1; j ++) {
first = first.getNext();
helper = helper.getNext();
}
//first 要出圈
System.out.print(first.getData() + "\t");
first = first.getNext();
helper.setNext(first);
// 原先的first自动回收
}
System.out.println("\n" + "最后圈里的小孩是:" + helper.getData());
}
}
运行结果如下:
12->13->14->15->16->17->(12)headnode
6
要出圈的小孩:
13 15 17 14 12
最后圈里的小孩是:16