时间:2021-07-01 10:21:17 帮助过:22人阅读
更多的类似问题是:n个人围成圈,依次编号为1,2,..,n,现在从1号开始依次报数,当报到m时,报m的人退出,下一个人重新从1报起,循环下去,问最后剩下那个人的编号是多少?
代码实现:
value = $value;
}
function addNode($node, $value){
	$lastNode = findLastNode($node);
	$nextNode = new Node();
	$nextNode->value = $value;
	$lastNode->nextNode = $nextNode;
}
/* 找到最后的节点 */
function findLastNode($node){
	if(empty($node->nextNode)){
		return $node;
	}else{
		return findLastNode($node->nextNode);
	}
}
/* 删除节点 必须head为引用传值 */
function deleteNode(&$head, $node, $m, $k = 1){
	if($k + 1 == $m){
		if($node->nextNode == $head){
			$node->nextNode = $node->nextNode->nextNode;
			$head = $node->nextNode;
			return $node->nextNode;
		}else{
			$node->nextNode = $node->nextNode->nextNode;
			return $node->nextNode;
		}
	}else{
		return deleteNode($head, $node->nextNode, $m, ++$k);
	}
}
/* 节点数 */
function countNode($head, $node, $count = 1){
	if($node->nextNode == $head){
		return $count;
	}else{
		return countNode($head, $node->nextNode, ++$count);
	}
}
function printNode($head, $node){
	echo $node->value . '  ';
	if($node->nextNode == $head) return;
	printNode($head, $node->nextNode);
}
function show($data){
	echo '';
	print_r($data);
	echo '
';
}
$head = new Node();
create($head, 1);
addNode($head, 2);
addNode($head, 3);
addNode($head, 4);
addNode($head, 5);
addNode($head, 6);
addNode($head, 7);
addNode($head, 8);
addNode($head, 9);
addNode($head, 10);
addNode($head, 11);
addNode($head, 12);
$lastNode = findLastNode($head);
$lastNode->nextNode = $head;
$count = countNode($head, $head);
$tmpHead = $head;
while ($count > 2) {
	$tmpHead = deleteNode($head, $tmpHead, 3, 1);
	$count = countNode($head, $head);
}
printNode($head, $head);
以上就介绍了 PHP实现单向链表解决约瑟夫环问题,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。