约瑟夫环问题

来源:互联网 发布:淘宝网安卓版 编辑:程序博客网 时间:2024/06/05 02:49
// DataStructure.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"typedef struct Student{int data;Student *next;}Node;void print(Node *head){if (head==NULL){return ;}Node *p=head;do{printf("%d\t",p->data);p=p->next;} while (p!=head);printf("\n");}void josephus(int n,int k,int m){Node *head=NULL;Node *p=head;for (int i = 1; i <= n; i++){Node *node=new Node();node->data=i;if (head==NULL){head=node;}else{p->next=node;}//循环node->next=head;p=node;}print(head);int i=1;p=head;Node *q=p;while (i<k){q=p;p=p->next;++i;}printf("%d\n",p->data);i=1;while (p!=NULL){while (i<m){++i;q=p;p=p->next;}if (p->next==p)//only one node{printf("%d\n",p->data);delete p;break;}else{Node *r=p;printf("%d->",r->data);q->next=p->next;p=p->next;delete r;}i=1;}}int _tmain(int argc, _TCHAR* argv[]){josephus(13,4,2);return 0;}

0 0
原创粉丝点击