DS循环链表—约瑟夫环

Description

N个人坐成一个圆环(编号为1 - N),从第S个人开始报数,数到K的人出列,后面的人重新从1开始报数。依次输出出列人的编号。 例如:N = 3,K = 2,S = 1。
2号先出列,然后是1号,最后剩下的是3号。
要求使用循环链表实现。

Input

第一行输入t,表示有t个测试用例;

第二行起,每行输入一组数据,包括3个数N、K、S,表示有N个人,从第S个人开始,数到K出列。

(2 <= N <= 10^6,1 <= K <= 10, 1 <= S <= N)

Output

出列的人的编号

Sample

Input
2
13 3 1
3 2 1
Output
3 6 9 12 2 7 11 4 10 5 1 8 13 
2 1 3 

#include<iostream>
using namespace std;
class Node {
public:
	int data;
	Node* next;
	Node() :data(0), next(nullptr) {}
	Node(int a) :data(a), next(nullptr) {}
};
class List {
public:
	Node* head = new Node();
	void insert(int t)
	{
		head->data = 0;
		Node* curr = head;
		for (int i = 1; i < t; i++)
		{
			Node* pnode = new Node(i);
			curr->next = pnode;
			curr = pnode;
		}
		curr->next = head;
	}
	void ysf(int m, int n)
	{
		Node* curr = head;
		Node* pnode = new Node();
		for (int i = 1; i < n; i++)
		{
			curr = curr->next;
		}
		while (curr->next != curr)
		{
			
			for (int i = 1; i < m; i++)
			{
				pnode = curr;
				curr = curr->next;
			}
			cout << curr->data + 1 << " ";
			pnode->next = curr->next;
			curr = curr->next;
		}
		cout << curr->data + 1 << " ";
	}

};

int main()
{
	int num;
	cin >> num;
	while (num--)
	{
		int t, m, n;
		cin >> t >> m >> n;		
		List list;
		list.insert(t);
		list.ysf(m, n);
		cout << endl;
	}

	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值