早教吧 育儿知识 作业答案 考试题库 百科 知识分享

请用JAVA写一个程序:设有n个人站成一排,每一个人有一编号i(1≤i≤n),从左向右“1、2、1、2、...”报数,数到1的人出列,数到2的人立即站到队伍的最右端。报数过程反复进行,直到n个

题目详情
请用JAVA写一个程序:
设有n个人站成一排,每一个人有一编号i(1≤i≤n),从左向右“1、2、1、2、...”报数,数到1的人出列,数到2的人立即站到队伍的最右端。报数过程反复进行,直到n个人都出列为止。已知n个人的原来的顺序,请写出他们的出列顺序。
▼优质解答
答案和解析
public class PersonQueue {
Person head = new Person(0);
Person pointer;
Person last;
public static void main(String[] args) {
new PersonQueue().onStart(5);
}

public void onStart(int count){
if(count <= 0){
throw new IllegalArgumentException();
}
pointer = head;
for (int i = 1; i <= count; i++) {
Person p = new Person(i);
p.setPrevious(pointer);
pointer.setNext(p);
pointer = p;
}
last = pointer;

this.onRun();
}
private void onRun(){
while(head.next != null){
pointer = head.next;
int index = 1;
while(pointer.next != null){
if(index % 2 == 1){
Person p = pointer;
p.count(1);
System.out.println(" i was removed");
pointer = p.next;
p.previous.setNext(pointer);
pointer.setPrevious(p.previous);

}
else if(index % 2 == 0){
Person p = pointer;
p.count(2);
System.out.println(" i was offered the last");
pointer = p.next;
p.previous.setNext(pointer);
pointer.setPrevious(p.previous);
last.setNext(p);
last = p;
last.setNext(null);

}

index++;
}

if(index == 1){
pointer.count(1);
System.out.println(" i was removed");
break;
}

}

}

// ===========================================================
// Inner Class
// ===========================================================
class Person{
int pid = 0;
Person next = null;
Person previous = null;
public Person(int id){
this.pid = id;
}
public int getId(){
return pid;
}
public void count(int num){
System.out.print("my pid is:"+pid+" and i say:"+num +" so ");
}
public void setNext(Person p){
this.next = p;
}
public Person next(){
return next;
}
public Person previous() {
return previous;
}
public void setPrevious(Person previous) {
this.previous = previous;
}

}
}
=========================result==================
my pid is:1 and i say:1 so i was removed
my pid is:2 and i say:2 so i was offered the last
my pid is:3 and i say:1 so i was removed
my pid is:4 and i say:2 so i was offered the last
my pid is:5 and i say:1 so i was removed
my pid is:2 and i say:2 so i was offered the last
my pid is:4 and i say:1 so i was removed
my pid is:2 and i say:1 so i was removed