约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
// 13_3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <conio.h> #include <string.h> #include <stdio.h> using namespace std; typedef struct LNode { int data; struct LNode *link; }LNode,*Linklist; void JOSEPHUS(int n,int k,int m) { //create the cycle link list Linklist p,l,curr,r; p = (Linklist)malloc(sizeof(LNode)); p->data = 0; p->link = p; curr = p; for (int i = 0; i < n; i++) { l = (Linklist)malloc(sizeof(LNode)); l->data = i; l->link = curr->link; curr->link = l; curr = l; } //p->link = curr; //find the first occurrence of k r = p; while (k--) { r = p; p = p->link; } while (n--) { for (int s = m - 1; s >= 0; s--) { r = p; p = p->link; } r->link = p->link; cout << "The deleted value is: " << p->data << endl; free(p); //prepare for next time while loop p = r; } } int _tmain() { JOSEPHUS(13,4,1); return 0; }原文链接:https://www.f2er.com/datastructure/383037.html