Solve the Joseph problem public class yuesefu{//define the nodes of the linked list public static class node{public int value;
Node Next;
public Node (int data) {this.value=data; }///Solve the Josephson problem/** head Ring List header node num reported number/public static node Yuesefu (node Head,int num) {if (head==null| | num<=0| |
Head.next==head) {return head;
//When the count is 1 o'clock, it must be the last number if (num==1) {Node p=head;
while (head.next!=p) {Node q=head;
Head=head.next; Q=null;
Deletes a linked list of nodes} return head; int t=0;
The location where the record list is reached while (head.next!=head)//When not the last node {++t;
if (t==num-1)//delete nodes {node P=head.next each time the number of reported nodes is Num;
Head.next=head.next.next;
P=null;
t=0;
} Head=head.next;
return head; /** advanced: When the ring list length is n, in O ((N) Complexity complete operation */public static node Nyuesefu (Node head,int num) {if head==null| | num<=0| |
Head.next==head) {return head;
//When the count is 1 o'clock, it must be left for the last number if (num==1) {Node p=head;
while (head.next!=p) {Node q=head;
Head=head.next; Q=null;
Deletes a linked list of nodes} return head;
int leng=1;
Node P=head;
while (P.next!=head) {++leng;
P=p.next;
} leng=getlive (Leng,num);
while (--leng!=0) {head=head.next;
}//Last node Head.next=head;
return head;
///Get new Old Joseph node relationship (Num (i) with num (i-1)) public static int getlive (int len,int num) {if (len==1)
{return 1;
Return (Getlive (len-1,num) +num-1)%num+1;
public static void Main (String []args) {//system.out.println ("Hello"); Tectonic Joseph Ring (1->2->3-≫4->1 node Node=new node (1);
Node.next=new Node (2);
Node.next.next=new Node (3);
Node.next.next.next=new Node (4);
Node.next.next.next.next=node;
Node Mode=yuesefu (node,1);
System.out.println (Mode.value);
Node Tnode=nyuesefu (node,2);
System.out.println (Tnode.value);
}
}