线性表应用:魔术师发牌与拉丁(Latin)方阵(循环链表)
题目描述: 有黑桃1到13,13张牌,成某种顺序,魔术师可以从1开始数 ,数1,背面朝上的13张牌第一张就是1,然后放到桌面上,然后从1开始数,把第一张放在所有牌下面,数到2,翻开,就是2,再放到桌子上,以此此类推 #include<stdio.h> #include<stdlib.h> #define LEN sizeof(LinkList) #define cardNum 13 typedef struct node { int data; struct node *next; }LinkList; LinkList *creatList() { LinkList *head = NULL; LinkList *s,*r; r = head; for(int i=1; i <= cardNum; i++) { s = (LinkList *)malloc(LEN); s->data = 0; if(head == NULL) { head = s; } else { r->next = s; } r = s; } r->next = head; return head; } void MagicCard(LinkList *head) { int i; int countNum = 2; LinkList *p; p = head; p->data = 1; while(1) { for(i=0; i < countNum; i++) //寻找作用 { p = p->next; if(p->data != 0) //那个地方已经有牌则从下一张开始 { p = p->next; i--; } } if(p->data == 0) { p->data = countNum; countNum++; if(countNum == 14) break; } } } int main(void) { int i; LinkList *p; p = creatList(); MagicCard(p); printf("魔术牌的顺序是:\n"); for(i=0; i < cardNum; i++) { printf("黑桃%d ",p->data); p = p->next; } return 0; } Latin 例如3阶的 1 2 3 2 3 1 3 1 2 自己实现: #include<stdio.h> #include<stdlib.h> #define LEN sizeof(LinkList) typedef struct node { int data; struct node *next; }LinkList; LinkList *CreatList(int num) //生成循环链表 { int i; LinkList *head = NULL; LinkList *p,*s; for(i = 1; i <= num; i++) { s = (LinkList *)malloc(LEN); s->data = i; if(head == NULL) { head = s; } else { p->next = s; } p = s; } p->next = head; return head; } int main(void) { LinkList *p; LinkList *s; int num; int i,j; printf("请输入想要创建的Latin维数:"); scanf("%d",&num); p = CreatList(num); printf(" %d维Latin:\n",num); for(i=0; i < num; i++) { for(j=0; j < num; j++) { printf("%3d",p->data); p = p->next; } p = p->next; printf("\n"); } return 0; }