根据约瑟夫斯问题,我必须编写一个程序,利用循环列表给出最后一个站立的人的输出。它似乎在大多数情况下都有效,但是,当我进入系列 7(人)1(起始位置),3(杀死计数)时。它在杀戮的中途被扔掉了。(大约当列表是 2357 时)我已经按照数字查看了几次代码,但无法弄清楚为什么在这次迭代中它杀死了 3 而不是 5。
import java.util.Scanner;
class Link{
public int itemData;
public Link next;
public Link(int itemNumber){
//initialize's data
itemData = itemNumber;
}
public void displayLink(){
System.out.print("{" + itemData + "}");
}
}
class LinkList{
private Link first; //first link
private Link last;
private Link current;
public LinkList getCurrent;
public LinkList(){
first = null;
last = null;
current = null;
}
public boolean isEmpty(){
return(first == null);
}
public void setCurrent(){
current = current.next;
}
public Link getCurrent(){
return current;
}
public void fillList(int listSize){
for(int i=1; i < listSize + 1; i++){
Link newLink = new Link(i);
if(isEmpty()){
first = newLink;
current = first;
}
else{
current.next = newLink;
newLink.next = first;
last = newLink;
setCurrent();
}
}
}
public Link find(int holder, int listSize){
Link marker = first;
for(int i = 0; i < listSize; i++){
if(marker.itemData == holder){
break;
}
else{
marker = marker.next;
}
}
return marker;
}
public void deleteEvery(int holder, int pass, int listSize){
while(listSize!= 1){
Link current = find(holder, listSize);
Link previous = first;
for(int i = 1; i < pass; i++){
current = current.next;
}
previous = current;
current = current.next;
if(current == first){
first = first.next;
}
else{
previous.next = current.next;
}
holder = current.next.itemData;
displayList(--listSize);
}
}
public void displayList(int listSize){
System.out.print("List:");
Link current = first;
for(int i = 1; i < listSize+1; i++){
current.displayLink();
current = current.next;
}
System.out.print("");
}
}
class Josephus{
public static void main(String[] args){
LinkList people = new LinkList();
Scanner input = new Scanner(System.in);
System.out.print("Please enter 3 integers (size, holder, passing).");
int listSize = input.nextInt();
int holder = input.nextInt();
int pass = input.nextInt();
people.fillList(listSize);
people.displayList(listSize);
people.deleteEvery(holder, pass, listSize);
}
}