标签:src 循环链表 com http include ima i++ 链表实现 约瑟夫环问题
约瑟夫环的问题和种类有很多,这是一道基本的约瑟夫环问题,通过单向循环链表实现模拟此过程。
代码如下:
#include<stdio.h> #include<stdlib.h> typedef struct Node { int num; int password; struct Node *next; }CircleNode,*CircleList; CircleList Create(int n); void Knockout(CircleList L,int n,int m); int main(void) { printf("Enter the upper limit m: "); int m; scanf("%d",&m); printf("Enter the number of people: "); int n; scanf("%d",&n); CircleList L=Create(n); printf("The order of knockout: "); Knockout(L,n,m); return 0; } CircleList Create(int n) { CircleList L=(CircleList)malloc(sizeof(CircleNode)); L->next=L; CircleNode *rear=L; printf("Enter the password for person 1-%d: ",n); for(int i=1;i<=n;i++) { CircleNode *p=(CircleNode*)malloc(sizeof(CircleNode)); scanf("%d",&p->password); p->num=i; rear->next=p; rear=p; } rear->next=L; return L; } void Knockout(CircleList L,int n,int m) { CircleNode *cur=L; CircleNode *prev=L; while(n--) { for(int i=1;i<=m;) { if(cur->next!=L) { prev=cur; cur=cur->next; } else { prev=L; cur=L->next; } ++i; } printf("%d ",cur->num); m=cur->password; prev->next=cur->next; free(cur); } } /* 测试集 输入: m=20 n=7 密码:3 1 7 2 4 8 4 输出: 6 1 4 7 2 3 5 */ /* void Print(CircleList L) { CircleNode *p=L->next; while(p!=L) { printf("%d ",p->num); p=p->next; } } */
标签:src 循环链表 com http include ima i++ 链表实现 约瑟夫环问题
原文地址:https://www.cnblogs.com/CuteyThyme/p/10679352.html