java solve joseph problem

/**
 * @Author Qingyu
 * @Function Joseph Problem Solving
 * @Time 2018.04.25
 */


package test;


public class Test {


public static void main(String[] args) {
// TODO Auto-generated method stub
Linklist linklist = new Linklist();
linklist.setLen(5);//Set the size of the linked list
linklist.creatLinklist();//Create a linked list
linklist.PrintLinklist();//Print the linked list
System.out.print("\nThe delete sequence is :");
Josephus josephus = new Josephus();
josephus.setm(2);//Set the node that
starts josephus.setn(2);//Number n next cycle
josephus.start();
}


}


class People {
int number;
People nextPerson=null;
public People(int num){
this.number=num;
}
}


class Linklist{
static int len=0;//链表大小
static People firstPeople=null;//链表头结点
People temp;
public void setLen(int len){
this.len=len;
} //初始化链表 public void creatLinklist(){  for(int i=1;i<=len;i++){ if(i==1){ People person=new People(i); this.firstPeople=person; this.temp=person; } else{ if(i==len){ People person=new People(i); temp.nextPerson=person; person.nextPerson=this.firstPeople; } else{ People person=new People(i); temp.nextPerson=person;


















temp=person;
}
} } } //Print linked list public void PrintLinklist(){ People temp = this.firstPeople; System.out.print("The current sequence is: "); for(int k=1;k<=len ;k++){ System.out.print(temp.number+" "); temp=temp.nextPerson; } } } class Josephus{ int m;//Start from the first person int n;//Number n public void setm (int m){ this.m=m; } public void setn(int n){ this.n=n; } public void start(){ //First find the location of the person who started People temp = Linklist.firstPeople ; for(int i=1;i<m;i++){ temp=temp.nextPerson;



























}
while(Linklist.len!=0){
//Next, we need to find the node to delete, because we want to delete that node, so we should know its previous node and next node
for(int j=1;j< n-1;j++){
temp=temp.nextPerson;
}
System.out.print(temp.nextPerson.number+" ");//Output the node to be deleted
People temp2=(temp.nextPerson).nextPerson;//To be The next node
to delete temp.nextPerson=temp2;//The previous node of the node to be deleted points to the next node to be deleted
temp=temp2;
Linklist.len--;
} } }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324846053&siteId=291194637