1.要求:有一群人围成一圈数数,逢3退1人,要求算出最后留下来的人的下标
2.用面向对象思想,有三个步骤:
(1)有哪些类:找名词--"有一群人围成一圈",所以有类People,PeopleCircle
(2)有哪些属性方法
(3)类的关系
3.代码:
package Test; public class Count3Quit1$2 { public static void main(String[] args) {
PeopleCircle pc = new PeopleCircle(500);
int countNum = 0; People del = pc.getLast(); //先把位置指向last,一开始计数就会指向第一个元素
while(pc.getCount() > 1){
countNum++;
del = del.getRight();//跟踪当前的元素位置,且到了末尾会自动从头开始跟踪
if(countNum == 3){
pc.delete(del);
countNum = 0;
}
}
System.out.println(pc.getCount());
System.out.println(pc.getFirst());
System.out.println(pc.getLast());
} } //要求:有一群人围成一圈数数,逢3退1人,要求算出最后留下来的人的下标
//用面向对象思想,有三个步骤:
//(1)有哪些类(2)有哪些属性方法(3)类的关系 //(1)有哪些类?找名词--"有一群人围成一圈",所以有类People,PeopleCircle
class People{ private int id;
private People left;
private People right; public People(int id) {
super();
this.id = id;
} public People getLeft() {
return left;
} public void setLeft(People left) {
this.left = left;
} public People getRight() {
return right;
} public void setRight(People right) {
this.right = right;
} @Override
public String toString() {
return "People-"+id;
}
} class PeopleCircle{ private int count = 0; public int getCount() {
return count;
} public PeopleCircle(int count) {
for(int i = 0; i < count ; i++){
add();
}
} private People first;
public People getFirst() {
return first;
} private People last; public People getLast() {
return last;
} public void add(){
People p = new People(count);
if(count <= 0 ){
p.setLeft(p);
p.setRight(p);
first = p;
last = p;
count++;
}else {
last.setRight(p);
p.setLeft(last);
p.setRight(first);
first.setLeft(p);
last = p;
count++;
}
} public void delete(People p){
if(count <= 0){
System.out.println("已经没有人!");
return;
}else if(count == 1){
first = last = null;
count--;
}else{
p.getLeft().setRight(p.getRight());
p.getRight().setLeft(p.getLeft()); if(p == first){
first = p.getRight();
}else if (p == last){
last = p.getLeft();
}
count--;
}
}
}
4.运行结果: