Josephus问题的链表实现

7 篇文章 0 订阅

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


#include <iostream>

struct node
{
	int data;
	node* next;
};

node* construct( node* head, int currentData, int max )
{
	node* current = new node();
	current->data = currentData;

	if( currentData == max )
	{
		current->next = head ;
	}
	else
	{
		current->next = construct( head, currentData + 1, max);
	}
	return current;
}


void print( node* current )
{
	std::cout << current->data << " " ;
	if( current->next->data < current->data )
	{
		return ;
	}
	print( current->next );
}

// include current
node* getNext( node* current, int step )
{
	node* temp = current ;
	node* parent = 0;
	for( int i = 1; i < step; i++ )
	{  
		parent = temp ;
		temp = temp->next ;
	}
	return parent;
}


void printJosephus(node* current, int step )
{
	node* parent = getNext( current, step );

	node* temp = parent->next ;
	std::cout << temp->data << " ";
	if( temp->next == parent )
	{
		// only two left now
		std::cout << parent->data << " ";
		parent->next = 0 ;
		delete temp ;
		delete parent ;
	}
	else
	{
		parent->next = temp->next;
		delete temp;
		printJosephus( parent->next, step );
	}
}


void main()
{
	std::cout << "Josephus Problem: " << std::endl;
	node* head = new node();
	int start = 1;
	head->data = start;
	head->next = construct( head, start + 1, 41 );
	// the list is
	print( head );
	std::cout << std::endl ;
	printJosephus( head, 3 );
	getchar();
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值