环形单链表的约瑟夫问题

描述:据说著名历史学家 Josephus 有过以下问题:在罗马人占领乔塔帕特后,39 个犹太人与 Josephus 及他的朋友躲到一个洞里面, 39 个犹太人决定宁死也不愿被敌人抓到,于是他们决定了一个自杀的方式,41 个人排成一个圈,由第一个人开始报数,报到 3 的人自杀,然后剩下的人再依次报数,报到三的人自杀,最后剩一个人可以选择自己的命运。这就是著名的约瑟夫问题。现在用环形单链表实现这个自杀过程。
过程:
1、如果链表为空或者是节点个数为1,或者 m 的值小于 1 则不用调整,直接返回。
2、在环形链表中遍历每个节点,不断转圈,不断让每个节点计数。
3、当报数达到 m 后,就删除当前报数的节点。
4、删除节点后将环连起来。
5、不断删除,直到只剩一个节点。

public class Node{
public int value ;
public Node next ;

public Node ( int data){
this . value = data ;
}
}

public Node josephusKilll (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 counnt = 0 ;
while (head != last){
if (++ counnt == m){
last. next = head. next ;
counnt = 0 ;
} else {
last = last. next ;
}
head = head. next ;
}
return head ;

}

参考资料:《程序员代码面试指南》左程云 著

猜你喜欢

转载自blog.csdn.net/young_1004/article/details/80551030