魔术师手中有A、2、3……J、Q、K十三张黑桃扑克牌。在表演魔术前,魔术师已经将他们按照一定的顺序叠放好(有花色的一面朝下)。魔术表演过程为:一开始,魔术师数1,然后把最上面的那张牌翻过来,是黑桃A;然后将其放到桌面上;第二次,魔术师数1、2;将第一张牌放到这些牌的最下面,将第二张牌翻转过来,正好是黑桃2;第三次,魔术师数1、2、3;将第1、2张牌依次放到这些牌的最下面,将第三张牌翻过来正好是黑桃3;……直到将所有的牌都翻出来为止。问原来牌的顺序是如何的。
#include <iostream> #include <cstdio> #include<cstdlib> #define CardCount 13 typedef struct node { int data; struct node *next; }sqlist, *linklist; //创建单链表 linklist CreateLinkList() { linklist head = NULL; linklist s; linklist r; int i; r = head; for (i = 1; i <= CardCount; i++) { s = (linklist)malloc(sizeof(sqlist)); s->data = 0; if (head = NULL) { head = s; } else { r->next = s; } r = s; } r->next = head; return head; } void Magician(linklist head) { linklist p; int j; int Countnumber = 2; p = head; p->data = 1; while (1) { for (j = 0; j < Countnumber; j++) { p = p->next; if (p->data != 0) { p->next; j--; } } if (p->data == 0) { p->data = Countnumber; Countnumber++; if (Countnumber == 14) { break; } } } } //销毁链表 void DestoryList(linklist *list) { linklist ptr = *list; linklist buff[CardCount]; int i = 0; while (i<CardCount) { buff[i++] = ptr; ptr = ptr->next; } for (i = 0; i < CardCount; ++i) { free(buff[i]); } *list = 0; } int main() { linklist p; int i; p = CreateLinkList(); Magician(p); printf("发牌顺序如下:\n"); for (i = 0; i < CardCount; i++) { printf("黑桃%d", p->data); p = p->next; } DestoryList(&p); return 0; }
