Josephus问题的链表实现

来源:互联网 发布:开源中国 cms 编辑:程序博客网 时间:2024/04/30 19:36

 据说著名犹太历史学家 Josephus有过以下的故事:在罗马人占领乔塔帕特后,39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被敌人抓到,于是决定了一个自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从,Josephus要他的朋友先假装遵从,他将朋友与自己安排在第16个与第31个位置,于是逃过了这场死亡游戏。


#include <iostream>struct node{int data;node* next;};node* construct( node* head, int currentData, int max ){node* current = new node();current->data = currentData;if( currentData == max ){current->next = head ;}else{current->next = construct( head, currentData + 1, max);}return current;}void print( node* current ){std::cout << current->data << " " ;if( current->next->data < current->data ){return ;}print( current->next );}// include currentnode* getNext( node* current, int step ){node* temp = current ;node* parent = 0;for( int i = 1; i < step; i++ ){  parent = temp ;temp = temp->next ;}return parent;}void printJosephus(node* current, int step ){node* parent = getNext( current, step );node* temp = parent->next ;std::cout << temp->data << " ";if( temp->next == parent ){// only two left nowstd::cout << parent->data << " ";parent->next = 0 ;delete temp ;delete parent ;}else{parent->next = temp->next;delete temp;printJosephus( parent->next, step );}}void main(){std::cout << "Josephus Problem: " << std::endl;node* head = new node();int start = 1;head->data = start;head->next = construct( head, start + 1, 41 );// the list isprint( head );std::cout << std::endl ;printJosephus( head, 3 );getchar();}