一、题目描述
N个人坐成一个圆环(编号为1 - N),从第S个人开始报数,数到K的人出列,后面的人重新从1开始报数。依次输出出列人的编号。 例如:N = 3,K = 2,S = 1。
2号先出列,然后是1号,最后剩下的是3号。
要求使用循环链表实现。
二、输入与输出
1.输入
第一行输入t,表示有t个测试用例;
第二行起,每行输入一组数据,包括3个数N、K、S,表示有N个人,从第S个人开始,数到K出列。
(2 <= N <= 10^6,1 <= K <= 10, 1 <= S <= N)
2
13 3 1
3 2 1
2.输出
出列的人的编号
3 6 9 12 2 7 11 4 10 5 1 8 13
2 1 3
三、参考代码
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class ListNode {
public:
int data;
ListNode* next;
ListNode* pr;
ListNode() { data = 0; next = NULL; pr = NULL; };
};
ListNode* ListInit() {
ListNode* phead = (ListNode*)malloc(sizeof(ListNode));
phead->next = phead;
phead->pr = phead;
return phead;
}
void ListPushBack(ListNode* phead, int x) {
ListNode* tail = phead->pr;
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
newnode->data = x;
tail->next = newnode;
newnode->pr = tail;
newnode->next = phead;
phead->pr = newnode;
}
void Listdel(ListNode* pos) {
pos->pr->next = pos->next;
pos->next->pr = pos->pr;
delete(pos);
}
void Listpri(ListNode* phead) {
ListNode* cur = phead->next;
while (cur != phead) {
cout << cur->data;
cur = cur->next;
}
}
int main() {
int sum;
cin >> sum;
int N, K, S;
while (sum--)
{
ListNode* phead = ListInit();
cin >> N >> K >> S;
for (int i = 1; i <= N; i++) {
ListPushBack(phead, i);
}
ListNode* cur = phead;
int i = 0;
for (i = 0; i < S - 1; i++) {
cur = cur->next;
if (cur->next == phead)
{
cur = cur->next;
}
}
while (N)
{
if (cur->next == phead) {
cur = cur->next;
}
for (i = 0; i < K - 1; i++) {
cur = cur->next;
if (cur->next == phead)
{
cur = cur->next;
}
}
ListNode* newnode = cur->next;
cout << newnode->data << " ";
cur->next = newnode->next;
delete newnode;
N--;
}
cout << endl;
}
return 0;
}