DS循环链表—约瑟夫环(Ver. I - A)

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
{
private:
	int value;
	Node* next;
public:
	Node():value(0) { }
	Node(int v) :value(v) { }
	void create(int n, int s)
	{
		Node* temp = this;
		int j = s;
		if (s > n)
			j = s % n;
		for (int i = 1; i <= n; i++)
		{
			temp->next = new Node(j);
			j++;
			if (j > n)
				j = 1;
			temp = temp->next;
		}
		temp->next = this;
	}
	void Delete(int n, int k)
	{
		int count = 0;
		Node* temp = this->next, *a = this;
		while (this->next != this)
		{
			if(temp->value != 0)
				count++;
			if (count == k)
			{
				cout << temp->value << " ";
				a->next = temp->next;
				count = 0;
			}
			else
			{
				a = a->next;
			}
			temp = temp->next;
		}
		cout << endl;
	}
};

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, k, s;
		cin >> n >> k >> s;
		Node* head = new Node;
		head->create(n, s);
		head->Delete(n, k);
	}

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值