Write a two-way loop linked list, get a counter, I define the time to three, automatically delete the current node, very simple.
PackageCom;ImportJava.util.Scanner;/** Joseph Ring problem, there is a circle of n individuals, counting to 3 of that person to dequeue, the next person continues from the beginning*/ Public classJosephus { Public Static voidMain (string[] args) {Scanner s=NewScanner (system.in); intn =Integer.parseint (S.nextline ()); Node First=NewJosephus (). Startrun (n); intCount = 1; while(First.next! =First ) { First=First.next; Count++; if(Count = = 3) {First.previous.next=First.next; First.next.previous=first.previous; First=First.next; Count= 1; }} System.out.println ("The last number left is:" +FIRST.N); } PublicNode Startrun (intN) {Node First=NewNode (); First.previous=NULL; FIRST.N= N;//This gives the list value, flashbacksNode current =First ; Node Last=First ; while((--n) >0) {Current.next=NewNode (); Current=Current.next; CURRENT.N=N; Current.previous=Last ; Last=Current ; } Current.next=First ; First.previous=Current ; returnFirst ; } classNode {intN; Node Next; Node previous; }}
Josephus Ring class problem, Java implementation