黑马程序员技术交流社区
标题:
一道以约瑟夫环为模型的问题
[打印本页]
作者:
人在旅途~东营
时间:
2015-6-2 20:03
标题:
一道以约瑟夫环为模型的问题
今天看了一道题,差点没吐了,总算明白了,跟大家分享下
由n个小孩围成一个首尾相连的圈报数。
*从第k个人开始,从1开始报数,报到m的人出圈,
*剩下的人继续从1开始报数,直到所有的人都出圈为止。
*对于给定的k,m和n,求出最后出圈的小孩.
package com.itcast.cyclink;
public class Test1 {
public static void main(String[] args) {
CycLink cycLink = new CycLink();
cycLink.setLen(100);
cycLink.createLink();
cycLink.setK(1);
cycLink.setM(14);
//cycLink.show();
cycLink.play();
}
}
class Child{
int no;
Child nextChild = null;
public Child(int no){
// 给一个编号
this.no = no;
}
}
//环形链表
class CycLink{
// 先定义一个指向链表第一个小孩的引用
// 第一个小孩是不能动的
Child firstchild = null;
Child temp = null;
int len = 0;//表示共有几个小孩
int k = 0;
int m = 0;
// 设置链表大小
public void setLen(int len){
this.len= len;
}
// 设置从第几个人开始数数
public void setK(int k){
this.k = k;
}
// 设置数m下
public void setM(int m){
this.m = m;
}
//开始play
public void play(){
// 首先找到跑龙套的人
Child temp = this.firstchild;
// 1.先找到开始数数的人
for (int i = 1; i < k; i++) {
temp = temp.nextChild;
}
while(this.len!=1){
// 2.数m下
for (int j = 1; j < m; j++) {
temp = temp.nextChild;
}
// 找到要出圈的前一个人
Child temp2 = temp;
while (temp2.nextChild!=temp) {
temp2 = temp2.nextChild;
}
// 3.将数到m的小孩退出圈
temp2.nextChild=temp.nextChild;
// 让temp指向下一个数数小孩
temp = temp.nextChild;
this.len--;
}
// 最后一个小孩
System.out.println("最后出圈的小孩是:"+temp.no);
}
// 初始化环形链表
public void createLink(){
for (int i = 1; i <= len; i++) {
if (i==1) {
// 创建第一个小孩
Child ch = new Child(i);
this.firstchild = ch;
this.temp = ch;
}else {
// 创建最后一个小孩
if (i==len) {
// 继续创建小孩
Child ch = new Child(i);
temp.nextChild = ch;
temp=ch;
temp.nextChild = this.firstchild;
}else {
// 继续创建小孩
Child ch = new Child(i);
temp.nextChild=ch;
temp = ch;
}
}
}
}
// 打印环形链表
public void show(){
// 定义一个跑龙套
Child temp = this.firstchild;
do {
System.out.print(temp.no);
temp=temp.nextChild;
} while (temp != this.firstchild );
}
}
复制代码
作者:
石头888
时间:
2015-6-2 20:18
学习学习!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2