约瑟夫(Josephus)问题

来源:互联网 发布:python赋值 编辑:程序博客网 时间:2024/06/03 13:35

#include <stdio.h>#include <stdlib.h>struct Node;typedef struct Node *PtrToNode;typedef PtrToNode List;typedef PtrToNode Position;struct Node{PtrToNode Previous;PtrToNode Next;int Element;};Position Delete(Position P)  {Position tmp;tmp = P->Next;P->Previous->Next = tmp;tmp->Previous = P->Previous;free(P);return tmp;}Position CreatDoubleList(){PtrToNode head,last,now;head = last = malloc(sizeof(struct Node));now = malloc(sizeof(struct Node));last->Element = -1;head->Element = -1;scanf("%d",&now->Element);while(now->Element != 0){last->Next = now;now->Previous = last;last = now;now = malloc(sizeof(struct Node));scanf("%d",&now->Element);}last->Next = head;head->Previous = last;free(now);return head;} void Josephus(List L,int m,int n){int i,count = 0;Position P;P = L->Next;while(n > 1){count = m % n;for(i = 0;i < count;i++){P = P->Next;if(P->Element == -1)P = P->Next;} printf("%d\n",P->Element);P = Delete(P);n--;}if(P->Element == -1){P = P->Next;printf("%d\n",P->Element);}elseprintf("%d\n",P->Element);}int main(){int m,n,i;List L;L = CreatDoubleList();scanf("%d%d",&m,&n);Josephus(L,m,n);return 0;}

这题解得甚不合我意,答案应该是对的,有时间再想想



博客园,双向链表解决的

循环链表--解决Josephus问题


C++实现的,用双链表解决约瑟夫问题

0 0