约瑟夫问题(循环链表)

据说著名犹太历史学家 Josephus有过以下的故事:在罗马人占领乔塔帕特后,39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被敌人抓到,于是决定了一个自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从。一开始要站在什么地方才能避免被处决?Josephus要他的朋友先假装遵从,他将朋友与自己安排在第16个与第31个位置,于是逃过了这场死亡游戏。

#include <iostream>
using namespace std;
struct Node
{
	int num;
	Node *next;
};
int main()
{
	Node *tail = NULL, *temp;
	for (int i = 1; i <= 41; i++)
	{
		temp = new Node;
		temp -> num = i;
		if (tail == NULL)
		{
			tail = temp;
			temp -> next = temp;
		}
		else
		{
			temp -> next = tail -> next;
			tail -> next = temp;
			tail = temp;
		}
	}
	temp = tail;
	do
	{
		Node *next;
		for (int i = 0; i < 2; i++)
		{
			temp = temp -> next;
		}
		next = temp -> next;
		temp -> next = next -> next;
		cout << next -> num << "死了\t";
		if (tail == next)
			tail = temp;
		delete next;
	} while (temp != temp -> next -> next);
	
	temp = tail;
	cout << endl;
	do
	{
		temp = temp -> next;
		cout << temp -> num << " ";	
	} while (temp != tail);
	cout << endl;
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值