魔术师发牌问题
1.问题描述:
魔术师手中有A、2、3……J、Q、K十三张黑桃扑克牌。在表演魔术前,魔术师已经将他们按照一定的顺序叠放好(有花色的一面朝下)。魔术表演过程为:一开始,魔术师数1,然后把最上面的那张牌翻过来,是黑桃A;然后将其放到桌面上;第二次,魔术师数1、2;将第一张牌放到这些牌的最下面,将第二张牌翻转过来,正好是黑桃2;第三次,魔术师数1、2、3;将第1、2张牌依次放到这些牌的最下面,将第三张牌翻过来正好是黑桃3;……直到将所有的牌都翻出来为止。问原来牌的顺序是如何的。
2.C++代码:
/*使用循环链表求解
解题思路:
1.创建含有13个结点单循环链表并将每个节点初值初始化为0;
2.用循环链表模拟魔术师发牌;
3.打印结果。
*/
#include<iostream>
using namespace std;
struct node{ //创建结点
int data;
node* next;
node (int data)
{
this->data=data;
}
node()
{}
};
typedef node* pointer;
pointer creatList() //创建并初始化循环链表
{
pointer head,current,newnode;
head=current=new node;
head->data=0;
int N=12;
while(N>=1)
{
newnode=new node(0);
current->next=newnode;
current=current->next;
N--;
}
current->next=head;
return head;
}
void Magician(pointer List) //模拟魔术师发牌
{
pointer ptr;
ptr=List;
ptr->data=1;
int card=2;
while(1)
{
for(int i=0;i<card;i++)
{
ptr=ptr->next;
if(ptr->data!=0)
i--;
}
if(ptr->data==0)
{
ptr->data=card++;
if(card>13)
break;
}
}
}
void Display(pointer List) //打印结果
{
pointer current=List;
pointer head=current;
while(current->next!=head)
{
cout<<current->data<<' ';
current=current->next;
}
cout<<current->data;
}
int main()
{
pointer List=creatList();
Magician(List);
cout<<"原来牌的顺序为:"<<endl;
Display(List);
return 0;
}