N个人围成一圈顺序编号,从1号开始按1、2、3......顺序报数,报p者退出圈外,其余的人再从1、2、3开始报数,报p的人再退出圈外,以此类推。 请按退出顺序输出每个退出人的原序号。
#include <iostream>
using namespace std;
struct Node
{
int data = -1;
struct Node* next = NULL;
};
Node* list(int n) //创立循环链表
{
int i = 0;
Node* head = new Node;
Node* list1;
list1 = head;
head->data = 1;
head->next = NULL;
for (i = 2; i <= n; i++) //创立后续节点
{
Node* list2 = new Node;
list2->data = i;
list2->next = NULL;
list1->next = list2;
list1 = list1->next;
}
list1->next = head; //首尾相连
return head;
}
int main()
{
int i = 0, j = 0, N = 0, p = 0;
cin >> N >> p;
Node* head, * temp = NULL;
head = list(N);
for (i = 0; i < N - 1; i++)
{
for (j = 1; j < p; j++)
{
temp = head;
head = head->next; //数人
}
cout << head->data<<' '; //输出出列的人
temp->next = head->next; //暂时存放下一位
delete head; //删除出列的人
head = temp->next; //将临时节点重新赋值给head
}
cout << head->data;
return 0;
}
网友评论