问题描述:一堆小孩围成一个圈,从第一个小孩开始数,每数到第三个便把第三个孩子删去,数到只剩一个小孩为止,并求该孩子的具体编号。

解决办法

1.

package test;
public class Compare {
public static void main(String[] args) {
boolean[] array=new boolean[];
for(int i=;i<array.length;i++) {
array[i]=true;
}
int leftcount = ;
int countnum = ;
int index = ; while(leftcount > ) {
if(array[index]) {
countnum ++;
if(countnum == ) {
countnum = ;
array[index] = false;
leftcount--;
}
}
index ++;
if(index == ) {
index = ;
}
}
for(int i=;i<array.length;i++) {
if(array[i]) {
System.out.println(i);
}
}
} }

Java解决小孩围圈问题-LMLPHP

2.

package test;

public class Studentcircle {
public static void main(String[] args) {
makecircle b=new makecircle();
int countnum=;
student m=b.first;
while(b.count>) {
countnum++;
if(countnum==) {
countnum=;
b.delete(m);
}
m=m.right;
}
System.out.println(b.first.id);
} }
class student{
int id;
student left;
student right;
}
class makecircle{
int count=;
student first,last;
makecircle(int n){
for(int i=;i<n;i++) {
add();
}
}
void add() {
student x= new student();
x.id=count;
if(count<=) {
first=x;
last=x;
x.left=x;
x.right=x;
}else {
last.right=x;
x.left=last;
x.right=first;
first.left=x;
last=x;
}
count++;
}
void delete(student x) {
if(count<=) {
return;
}else if(count==) {
first=last=null;
}else {
x.left.right=x.right;
x.right.left=x.left; if(x==first) {
first=x.right;
}else if(x==last) {
last=x.left;
}
}
count --;
} }

Java解决小孩围圈问题-LMLPHP

05-08 08:18