Code implementation of Joseph ring

本文介绍了一个数学应用问题——约瑟夫环的C++实现方法。该问题涉及一定数量的人围成一圈,并按特定规则逐个淘汰,直到最后一个人被淘汰为止。文中提供了一份完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Joseph ring is a mathematical application of the problem: known n individuals (represented by numbers 1, 2, 3,..., n) sit around a round table. K from a number of people start off, the man out of the line to the m; his next person and from 1 to start off, count to m that another person out; so law be repeated until all of the people out around the table.

#include <iostream>
using namespace std;
struct Node
{
	int data;
	struct Node* next;
};
int main()
{
	int m,n;
	Node *head,*rear,*p,*q,*s;
	head = new Node;
	p = new Node;
	rear = head;
	
	cout<<"Please input the number of people:";
	cin>>n;
	cout<<"Please input the number of people out line:";
	cin>>m;
	
	//the head node does't store the data and does only turnover
	for(int i=1;i<n+1;++i)
	{
		s = new Node;
		s->data = i;
		rear->next = s;
		rear = s;
		rear->next = head->next;
	}
	int k = 0;
	//record node data
	int record=0;
	p = head->next;
	//the next node of the last is itself
	while(p&&p->next!=p)
	{
		k++;
		
		//when m-1 appeared,delete the it's next node 
		if(k==(m-1))
		{
			k = 0;
			q = new Node;
			q = p->next;
			p->next = q->next;
			p = p->next;	//skip the node to be deleted
			record = p->data;
			delete q;
		}
		else
			p = p->next;
	}
	cout<<"result is "<<record<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值