500個人圍成一個圈子,數夠3人,就退出1個,問最后剩下的是幾號?
????????檢驗先有5個人,應該留下第4個人,由于是數組,所以第四個人的下標是3.
/*achieve the funtion :count 3 kids, the quit the third kid
use the object thinking */public class Test{public static void main(String[] args) {KidCircle kc = new KidCircle(5);int countNum = 0;Kid k = kc.first;while(kc.count > 1){countNum ++;if(countNum ==3){countNum =0;kc.delete(k);}k = k.right;}System.out.println(kc.first.id); }
}/* define class Kid*/
class Kid{int id;Kid left; //left is means the current kids'left kid Kid right; //right is means the current kids'right kid
}/* define class KidCircle*/
class KidCircle{int count = 0; //mean the circles'numberKid first,last; //define the circles' first kid and last kid.KidCircle(int n){//Constructor :new n numbers kid circlefor(int i = 0;i<n;i++){add();}}/*add a kid in the last kids'right*/void add(){/*first: new a kid;id = count*/Kid k = new Kid();k.id = count;/*if no kid in the circle ,the new kid is the first kid and is the last kid*/if(count <=0){first = k;last = k;k.left = k;k.right = k;}/*if has some kids in the circle,the new kid will stand at the last kids'right,and the new kids'left is the last kid. another: the new kids'right is the first kids'lest*/else{last.right = k;k.left = last;k.right = first;first.left = k;last = k;}count ++;}void delete(Kid k){if(count <= 0){return;}else if(count == 1){first = last =null;}else{k.left.right = k.right;k.right.left = k.left;if(k == first){first = k.right;}else if(k == last){last = k.left;}}count --;}
}