C语言的Josephus环问题
Josephus环问题用C语言怎么解决,可否不用链表.只用数组能否可行.我看过一个只用了一个inta[2]就解决的可是不懂那种算法....
Josephus环问题用C语言怎么解决,可否不用链表.只用数组能否可行.我看过一个只用了一个int a[2]就解决的 可是不懂那种算法.
展开
展开全部
//循环链表解决 #include <stdio.h> #include <stdlib.h> typedef struct LNode { int data; struct LNode *next; }LNode; void josephus(int n, int k, int m) { LNode *head, *r, *list, *curr; /************create the circylar list***********/ head = (LNode *)malloc(sizeof(LNode)); head->data = 1; head->next = head; curr = head; int i; for(i=1; i<n; i++) { LNode *p = (LNode *)malloc(sizeof(LNode)); p->data = i+1; p->next = curr->next; curr->next = p; curr = p; } int x; list = head; while(--k) { r = list; list = list->next; } printf("%d\t%d\n", list->data, r->data); while(n--) { int j; for(j=0; j<m-1; j++) { r = list; list = list->next; } r->next = list->next; printf("%d\t", list->data); free(list); list = r->next; //list points to the next element which had been deleted } } int main() { int n, k, m; printf("Please input the total of the people in Josephus circle: "); scanf("%d", &n); printf("Please input the starting position: "); scanf("%d", &k); printf("Please input the dead number: "); scanf("%d", &m); josephus(n, k, m); printf("\n"); return 0; }
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询