约瑟夫问题:
已知 n 个人(以编号1,2,3…n分别表示)围坐在一张圆桌周围。从编号为 k 的人开始报数,数到 m 的那个人出圈;他的下一个人又从 1 开始报数,数到 m 的那个人又出圈;依此规律重复下去,直到剩余最后一个胜利者。
class CircularLinkedList{
Person head = null;
public void add(Person person){
if (head == null){
head = person;
head.next = head;
return;
}
Person temp = head;
while(temp.next != head && temp.next != null){
temp = temp.next;
}
temp.next = person;
person.next = head;
}
public Person get(int num){
if (num < 0 || num > length() - 1){
throw new RuntimeException("Input data is wrong");
}
Person temp = head;
while(num != 0){
temp = temp.next;
num--;
}
return temp;
}
public Person delete(int num){
isEmpty();
if (head.num == num){
Person p = head;
Person temp = head;
while(temp.next != head){
temp = temp.next;
}
if (head.next != null){
head = head.next;
temp.next = head;
}else{
head = null;
}
return p;
}
Person temp = head;
while(temp.next != head){
if (temp.next.num == num){
Person p = temp.next;
temp.next = temp.next.next;
return p;
}
temp = temp.next;
}
throw new RuntimeException("LinkedList do not have this person");
}
public int length(){
int count = 0;
Person temp = head;
if (head == null){
return 0;
}
if (head.next == null){
return 1;
}
while(temp.next != head){
count++;
temp = temp.next;
}
return count + 1;
}
public void show(){
isEmpty();
Person temp = head;
System.out.println(temp);
while(temp.next != head){
temp = temp.next;
System.out.println(temp);
}
}
public void isEmpty(){
if (head == null){
throw new RuntimeException("LinkedList do not have data");
}
}
public Person getHead(){
return head;
}
public void josephus(int startNum, int count, int num){
if (head == null || startNum < 1 || startNum > num){
throw new RuntimeException("Input data is wrong");
}
Person temp;
if (startNum == 1){
temp = head;
while(temp.next != head){
temp = temp.next;
}
}else{
temp = get(startNum - 2);
}
int counter = 1;
while (num != 0){
if (counter == count){
Person p = temp.next;
temp.next = temp.next.next;
counter = 1;
}
temp = temp.next;
num--;
counter++;
}
System.out.println(temp);
}
}
|