围圈淘汰逃离死亡问题 && 双向循环链表

解决问题:


N个人一二三报数,报三的出去,余下重新报,求最后剩下人的编号

用到双向循环链表

代码

#include <iostream>

#define list_length 41
#define			  N	 3

namespace Myspace
{
	using std::cout;
	using std::endl;

	typedef struct node
	{
		int num;
		node* next;
		node* front;

	}node;

	node* InitList(int root_num = 0)
	{
		node* head = (node*)malloc(sizeof(node));
		node* p_node = head;

		if (head)
		{
			head->num = root_num;
			head->next = NULL;
			for (int i = 1; i < list_length; i++)
			{
				node* new_node = (node*)malloc(sizeof(node));
				if (new_node)
				{
					new_node->front = p_node;
					p_node->next = new_node;
					new_node->num = ++root_num;
					p_node = new_node;

					if (i == list_length - 1)
					{
						head->front = new_node;
						new_node->next = head;
						return head;
					}
					else { new_node->next = NULL; }
				}
				else { return NULL; }
			}
		}
		else { return NULL; }
	}

	int get_rest(int length = list_length, int n = N)
	{
		int res = 0;

		while (1)
		{
			if (0 == length / n) { res = length; break; }
			length = length - length / n;
		}
		return res;
	}

}

using namespace Myspace;

int main()
{
	int rest = get_rest();
	int temp = 0;
	node* p_temp = (node*)malloc(sizeof(node));
	node* List = InitList(1);
	int num = 1;

	for (int i = 0; i < 1000000; i++)
	{
		if (i > list_length && List->front->num > List->num) { cout << endl << endl; }

		temp = List->num;

		for (int j = 0; j < rest; j++) { p_temp = List->next; }

		if (p_temp->num == temp) { free(p_temp); break; }

		if (num == N)
		{
			List->front->next = List->next;
			List->next->front = List->front;
			List = List->next;
			num = 1;
		}
		else
		{
			cout << List->num << "\t" << num++ << endl;
			List = List->next;
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T h a t

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值