拉丁方阵是一种n×n的方阵,方阵中恰有n种不同的元素,每种元素恰有n个,并且每种元素在一行和一列中 恰好出现一次。著名数学家和物理学家欧拉使用拉丁字母来作为拉丁方阵里元素的符号,拉丁方阵因此而得名。
代码思路简介:使用单循环链表来实现输出拉丁方阵。
在输出第一行的时候,从第一个元素开始输出,会输出至循环单链表的最后一个元素;
在输出第二行的时候,从第二个元素开始输出,会输出至循环单链表最后一个元素后,在输出循环单链表的第一个元素(因为每行的元素都是n个);
直到在输出第n行的时候,先输出最后一个元素,然后从循环单链表的第一个元素输出至n-1个元素。
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 typedef struct Node{ 5 int data; 6 struct Node* next; 7 }Node,*LinkList; 8 9 void CreateSimpleCycleList_tail(LinkList *L,int number){ 10 /* 创建一个单循环链表,没有头结点,尾指针指向第一个节点。 11 * */ 12 int count; 13 LinkList new,temp; 14 *L = (LinkList)malloc(sizeof(struct Node)); 15 if(!(*L)){ 16 printf("Error:malloc\n"); 17 exit(1); 18 } 19 (*L)->next = *L; //初始化了链表 20 for(count = 1; count <= number; count++ ){ 21 new = (LinkList)malloc(sizeof(struct Node)); 22 if(!new){ 23 printf("Error:malloc\n"); 24 exit(1); 25 } 26 new->data = count; 27 new->next = (*L)->next; 28 (*L)->next = new; 29 *L = new; 30 } //创建了单循环链表,有头结点 31 temp = (*L)->next; 32 (*L)->next = temp->next; 33 *L = temp->next; 34 free(temp); //将头结点删除 35 } 36 void ShowLatinSquare(LinkList L,int number){ 37 /* 38 * 输出拉丁方阵:count_Out是外循环计数共number次(number是单链表的长度), 39 * 是控制拉丁方阵的行数。count_In是内循环的次数,共number次,输出每一行。 40 * */ 41 int count_Out = 1,count_In; 42 LinkList temp = L; 43 while(count_Out <= number){ 44 count_In = 1; 45 while(count_In <= number){ 46 printf("%d ",L->data); 47 count_In++; 48 L = L->next; 49 } 50 printf("\n"); 51 L = L->next; //输出完一行后,L要后移两个位置 52 //但是48行代码已经移动一个,在这 53 //后移一个即可。 54 count_Out++; 55 } 56 } 57 int main(){ 58 int order; 59 LinkList L; 60 printf("please enter the order of Latin Square: "); 61 scanf("%3d",&order); 62 CreateSimpleCycleList_tail(&L,order); 63 ShowLatinSquare(L,order); 64 return 0; 65 }