尾插法和循环链表。
#include <stdio.h> #include <stdlib.h> typedef struct CircleLinkList { int data; struct CircleLinkList * next; }circleLinkList; int main() { circleLinkList * h, * r, * s; circleLinkList * L; int n, num; printf("请输入参与约瑟夫环的总人数及淘汰者编号:"); scanf("%d %d",&n,&num); h = (circleLinkList *)malloc(sizeof(circleLinkList)); r = h; for(int i = 0; i < n; i++) // 尾插法建立链表 { s = (circleLinkList *)malloc(sizeof(circleLinkList)); s -> data = i + 1; // 为参与人员编号 r -> next = s; // 中间过程分配的空间插到尾指针后面 r = s; } r -> next = NULL; L = h -> next; while(L) { printf("%d ",L -> data); L = L -> next; } r -> next = h -> next; L = h -> next; while(L -> next != L) { for(int j = 1; j < num - 1; j++) { L = L -> next; } L -> next = L -> next -> next; L = L -> next; } puts(" 最终胜利者:"); printf("%d ",L -> data); return 0; }
Output:
本段代码其本质都是用第一段代码中的主要方法 尾插法 来建立链表的):
#include <stdio.h> #include <stdlib.h> typedef struct CircleLinkList { int data; struct CircleLinkList * next; }circleLinkList; int main() { circleLinkList * h = NULL, * p, * q; int n , num; printf("请输入参与人数及淘汰编号:"); scanf("%d %d",&n,&num); for(int i = 0; i < n; i++) { p = (circleLinkList *)malloc(sizeof(circleLinkList)); if(h == NULL) h = p; else q -> next = p; p -> data = i + 1; p -> next = NULL; q = p; } q -> next = h;//循环条件 while(h != h -> next) { for(int i = 1; i < num - 1; i++) h = h -> next; h -> next = h -> next -> next; h = h -> next; } puts("最终胜利者:"); printf("%d ",h -> data); return 0; }