有12个人围成一圈,标号1~12,从其中一人开始,按顺时针方向1至K报数,报到K的人被淘汰出局,再从被淘汰者后面第一人开始同样报数,报到K者同样被淘汰,这样一直报下去….输出每轮淘汰的人的序号和后剩下的人的序号数
下面是我写的程序:
#include<iostream>
using namespace std;
class node
{
public:
int num;
node*next;
};
void print(node*h, node*t)
{
node*curr = h;
for (; curr != t; curr = curr->next)
{
cout << curr->num << " ";
}
cout << t->num <<endl;
}
int main()
{
node*head, *tail, *temp;
head = new node;
head->num = 1;
tail = head;
for (int i = 2; i <= 12; i++)//////////////////////////////创建环形,记下来好了
{
temp = new node;
temp->num = i;
temp->next = head;
tail->next = temp;
tail = temp;
}
cout << "Data";
print(head, tail);
int k;
cin >> k;
int count = 0;
while (count < 11)
{
for (int i = 1; i < k;i++)//////////////////////一直数到下一个被删除的,因为是环,所以不会出错。
{
temp = temp->next;
}
cout << temp->next->num<< "=>";
if(temp->next->num == head->num)
{
head = temp->next->next;
}
if(temp->next->num == tail->num)/////////////////如果头尾被删除,头向后移,尾向前移!!!!!!!!!!!!
{
tail = temp;
}
temp->next = temp->next->next;
if (head ==tail)////////////////////////////////////只有一个时,break,否则一直输出最后一个数!!!!!
{
cout << head->num;
break;
}
node*curr = head;
for (; curr != tail;curr = curr->next)
{
cout << curr->num << " ";
}
cout << tail->num <<endl;
count++;
}
}