约瑟夫环
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 #define Error 0 5 #define OK 1 6 typedef int ElemType; 7 typedef int status; 8 9 typedef struct Node 10 { 11 ElemType data; 12 struct Node *next; 13 }Node; 14 15 //创建约瑟夫环 16 17 status Create(Node** node ,int n) 18 { 19 Node* head = (Node*)malloc(sizeof(Node)); 20 Node *p,*s; 21 p = head; 22 int i=1; 23 24 if(n<1) 25 return Error; 26 while(i <= n) 27 { 28 s= (Node*)malloc(sizeof(Node)); 29 s->data= i++; 30 p->next =s; 31 p = s; 32 } 33 s->next = head->next; 34 *node = (head->next); 35 free(head); 36 return OK; 37 } 38 39 void print(Node *node) 40 { 41 Node* s = node; 42 do 43 { 44 printf("%d\n",s->data); 45 s = s->next; 46 }while(s != node); 47 } 48 void main() 49 { 50 Node *list; 51 int n = 41; 52 int m = 3; 53 int i; 54 Create(&list,n); 55 //print(list); 56 Node* temp; 57 58 m %=n; 59 60 while(list != list->next) 61 { 62 for(i = 1; i<m -1;i++) 63 { 64 list = list->next; 65 } 66 67 printf("%d->",list->next->data); 68 temp = list->next; 69 list->next = temp->next; 70 71 free(temp); 72 73 list = list->next; 74 } 75 76 printf("%d\n",list->data); 77 }