約瑟夫環問題:一圈共有N個人,開始報數,報到M的人自殺,然后重新開始報數,問最后自殺的人是誰?
//鏈表實現
public class Node{
public int value;
public Node next;
public Node(int data){
this.value=data;
}
}
public Node josephuskill(Node head,int m){
if(head==null||head.next==head||m<1){
return head;
}
Node last=head;
while(last.next!=head){
last=last.next;
}
int count=0;
while(head!=last){
if(++count==m){
last.next=head.next;
count=0;
}
else{
last=last.next;
}
head=last.next;
}
return head;
}