拉丁方陣是一種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 }
