Description
桌上有一叠牌,从第一张牌(即位于顶面的牌)开始从上往下依次编号为1~n。当至少还剩两张牌时进行以下操作:把第一张牌扔掉,然后把新的第一张放到整叠牌的最后。输入n,输出每次扔掉的牌,以及最后剩下的牌。
Input
第一行为一个整数t(0<t<40),表示测试用例个数。以下t行每行包含一个整数n(0<n<40),为一个测试用例的牌数。
Output
为每个测试用例单独输出一行,该行中依次输出每次扔掉的牌以及最后剩下的牌,每张牌后跟着一个空格。
Sample Input
2 7 4
Sample Output
1 3 5 7 4 2 6 1 3 2 4
#include<iostream>
using namespace std;
struct Node
{
Node* next;
int data;
};
Node* Create(int n)
{
Node* head = new Node;
Node*p, *pre;
head->next = NULL;
pre = head;
for (int i = 1; i<=n; i++)
{
p = new Node;
p->data = i;
p->next = NULL;
pre->next = p;
pre = p;
}
return head;
}
void Top(Node*head)
{
Node*p = head->next;
int top;
top = head->next->data;
cout << top << " ";
head->next = head->next->next;
delete p;
}
void Two(Node *head)
{
Node*q = head->next;
head->next = q->next;
Node*p = head;
while (p->next)
{
p = p->next;
}
p->next = q;
q->next = NULL;
}
int main()
{
int m;
cin >> m;
while (m-->0)
{
int n;
cin >> n;
Node*h = Create(n);
while (n-- >= 2)
{
Top(h);
Two(h);
}
cout << h->next->data << " ";
cout << endl;
delete h;
}
return 0;
}