约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
自己编写的:
#include <stdio.h>
struct ysf_node
{
struct ysf_node* prev;
struct ysf_node* next;
int index;
};
void create_ysf_list(struct ysf_node* head, unsigned int number)
{
struct ysf_node* tmp_prev;
unsigned int tmp_number = 1;
struct ysf_node *node;
head->prev = head;
head->next = head;
head->index = 1;
tmp_prev = head;
number --;
while(number> 0)
{
tmp_number ++;
node = (struct ysf_node *)malloc(sizeof(struct ysf_node));
node->prev = tmp_prev;
node->next = head;
tmp_prev->next = node;
tmp_prev = node;
node->index = tmp_number;
number --;
}
head->prev = node;
printf("Create YSFH successful!\n");
}
void del_bad_index(struct ysf_node* head, unsigned int bad_index,unsigned int number)
{
unsigned int tmp_index = 0;
unsigned int tmp_number = 1;
struct ysf_node* bad_node;
while(number > 1)
{
printf("Delete bad people:\n");
bad_node = head;
while(tmp_index < (bad_index-1))
{
bad_node = bad_node->next;
tmp_index++;
}
//delete bad_node
bad_node->prev->next = bad_node->next;
bad_node->next->prev = bad_node->prev;
head = bad_node->next;
bad_node->prev = bad_node;
bad_node->next = bad_node;
printf("%d: Bad people : %d\n",tmp_number, bad_node->index);
free(bad_node);
bad_node = NULL;
tmp_index = 0;
number --;
tmp_number++;
}
printf("Winner: %d\n",head->index);
}
void del_ysf_list(struct ysf_node* head)
{
free(head);
head = NULL;
}
int main()
{
unsigned int number;
unsigned int bad_index;
struct ysf_node head;
//get people number and bad index
printf("total people(more than 0): ");
scanf("%u",&number);
printf("the index of bad people(more than 0): ");
scanf("%u",&bad_index);
//create ysfh
create_ysf_list(&head, number);
//delete the bad people
del_bad_index(&head, bad_index,number);
del_ysf_list(&head);
return 0;
}