Josephus问题

来源:互联网 发布:linux系统rpm 编辑:程序博客网 时间:2024/05/23 19:16
int  josephus( int ring_num, int pass_num ){inti;node*first, *previous;node*next_node;node*who_has_token;first =( node * )malloc( sizeof( node ) );assert( first != NULL );first->next = NULL;first->value = 1;first->coef = TOKEN;previous = first;for( i = 2; i <= ring_num; i++ ){next_node = ( node * )malloc( sizeof( node ) );assert( next_node != NULL );next_node->coef = 0;next_node->value = i;next_node->next = NULL;previous->next = next_node;previous = next_node;}/*闭合环*/next_node->next = first;who_has_token = first;previous = next_node;/*对pass_num取余,这样就不会有多于一圈的传递,对于M很多的可以节省很多时间*/pass_num = pass_num % ring_num;while( who_has_token->next != who_has_token ){node*temp;/* 传递pass_num次*/for( i = 0; i < pass_num; i++ ){who_has_token->next->coef = TOKEN;who_has_token->coef = 0;previous = who_has_token;who_has_token = who_has_token->next;}/*删除拥有TOKEN的节点*/temp = who_has_token;/*显示节点删除的顺序*/printf( "%4d", who_has_token->value );previous->next = who_has_token->next;who_has_token = who_has_token->next;who_has_token->coef = TOKEN;free( temp );}return who_has_token->value;}TOKEN其实没有必要,只要有who_has_token指针就行了