约瑟夫环问题

来源:互联网 发布:java连接数据库的代码 编辑:程序博客网 时间:2024/06/04 23:33
/*******************************************************************************约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。n = 9,k = 1,m = 5【解答】出局人的顺序为5,1,7,4,3,6,9,2,8。解决问题的核心步骤:(程序的基本算法)⒈建立一个具有n个链结点,无头结点的循环链表;⒉确定第1个报数人的位置;⒊不断地从链表中删除链结点,直到链表为空。********************************************************************************/#include <stdio.h>#include <stdlib.h>#include <iostream>using namespace std;typedef struct ListNode{int data;struct ListNode* next;}node, *pnode;void joseph(int n, int m, int k){//建立循环链表pnode head = NULL;node *pnew, *prear;for(int i=1; i<=n; i++){pnew = (node*)malloc(sizeof(node));pnew->data = i;pnew->next = NULL;if(head == NULL){head = pnew;prear = pnew;}else{prear -> next = pnew;prear = pnew;}}prear->next = head;//确定第1个报数人的位置node* cur = head;while(--k){cur = cur->next;}//不断地从链表中删除链结点,直到链表为空。node* ptr;while(n--){for(int j=m-1; j>0; j--){ptr = cur;cur = cur->next;}//delete the nodecout<<cur->data<<"\t";ptr->next = cur->next;cur = cur->next;}cout<<endl;}int main(){joseph(9,5,2);return 0;}

原创粉丝点击