Today watching video tutorial inadvertently saw a number 3 minus 1 of the problem, Baidu's discovery called Joseph Ring problem, and then wrote the program, the problem is roughly described as follows:
A group of children with numbered child hand in a circle, the beginning of the number of children 1, his right number 2, and then the right number 3, the number of children out of N, and then from the next child began to continue to count 1, the number of children out of N, so cycle ... What's the number of children left behind?
I wrote a two-way loopback list in Java here represents a circle, in which the kid is a linked list node, he has a left fellow, a right fellow, and an ID. The two-way list also defines the Add node method for adding (), deleting the node method Delete (), the team first child firstkid, the tail child lastkid, and the length of the table count.
classkidcircle{Private intcount; Kid Firstkid; Kid Lastkid; Kidcircle (intnum) {Count= 0; for(inti=0;i<num;i++) {Add (); } } Private voidAdd () {Kid k=NewKid (); K.id= Count+1; if(count==0) {Lastkid=K; Firstkid=K; } Else{k.left=Lastkid; K.right=Firstkid; Lastkid.right=K; Firstkid.left=K; Lastkid=K; } Count++; } Public voidDelete (Kid k) {if(count<=1){ return; } Else{Count--; K.left.right=K.right; K.right.left=K.left; if(k = =firstkid) {Firstkid=K.right; }Else if(k==lastkid) {Lastkid=K.left; } } } Public intGetSize () {returncount; }}
The Kid class is as follows:
class kid{ Kid left; Kid right; int ID;}
And then in the main method, I'm assuming that the number is 3 to eliminate a child, and then altogether 500 people:
Public class count3quit { publicstaticvoid main (string[] args) { new kidcircle (+); = Kc.firstkid; while (Kc.getsize () >1) { kc.delete (currentKid.right.right); = currentKid.right.right; } System.out.println (Kc.firstKid.id); }}
Final result: 436.
Have time to review things in the data structure.
"Java Program" Joseph Ring