标签:circularKinkedList int 环形 约瑟夫 链表 CircularKinkedList null public
public class CircularKinkedListDemo {
//测试
public static void main(String[] args) {
CircularKinkedList circularKinkedList = new CircularKinkedList();
circularKinkedList.countBoy(1, 10, 3);
}
}
//定义链表
class CircularKinkedList {
private Children first = null; //定义头指针,指向环形链表头部
public void add(int nums) {
if (nums < 1) {
System.out.println("参数不合法");
return;
}
Children temp = null; //中间变量
for (int i = 1; i <= nums; i++) {
Children children = new Children(i);
if (i == 1) { //第一个元素,头指针指向自己形成环
first = children;
first.setNext(first);
temp = first; //头指针不能动,用中间变量记录
} else { //将节点插入
temp.setNext(children);
children.setNext(first);
temp = children;
}
}
}
//遍历链表
public void showBoy() {
if (first == null) {
System.out.println("空的");
return;
}
Children temp = first; //从头开始
while (true) {
System.out.println(temp);
temp = temp.getNext();
if (temp == first) { //再一次到达头链表遍历结束
break;
}
}
}
//约瑟夫问题
public void countBoy(int startIndex, int muns, int num) {
if (startIndex < 1 || muns < 1 || num < 1) {
System.out.println("参数不合法");
return;
}
add(muns); //创建链表
Children temp = first; //中间变量用来上一个位置
while (true){ //初始化temp位置
temp = temp.getNext();
if (temp.getNext() == first) {
break;
}
}
//遍历叫号
while (true) {
for (int i = 0; i < num - 1; i++) { //移动节点
temp = first;
first = first.getNext();
}
System.out.println(first); //当前被叫到的节点
temp.setNext(first.getNext());
first = first.getNext();
if (first.getNext() == first) { //直到自己指向自己结束
System.out.println(first);
break;
}
}
}
}
//定义节点
class Children {
private int no;
private Children next = null;
public Children(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Children getNext() {
return next;
}
public void setNext(Children next) {
this.next = next;
}
@Override
public String toString() {
return "编号" + no;
}
}
标签:circularKinkedList,int,环形,约瑟夫,链表,CircularKinkedList,null,public 来源: https://www.cnblogs.com/lucfox/p/16524704.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。