int main()
{
int people = 19;
Node *head_node = create_ring(people);
printf("%d/n",head_node->data);
int x = game_start(head_node,3,people);
printf("\n%d", x);
return 0;
}
Node *create()
{
Node *p = (Node *)malloc(sizeof(Node));
assert(p != NULL);
p->next = NULL;
p->prev = NULL;
return p;
}
bool insert_tail(Node **head_node, Node *node)//传过来的只是指向Node结点的地址指针
{
if (node == NULL)
{
return false;
}
if (*head_node == NULL)//在申请之时,对该指针进行NULL初始化
{
(*head_node) = node;
}
else
{
Node *p = *head_node;
while(p->next != NULL)
{
p = p->next;
}
p->next = node;
node->prev = p;
}
return true;
}
void show(Node *head_node)
{
assert(head_node != NULL);
int i=0;
while(head_node->next != NULL)
{
printf("%d---%d\n", i, head_node->data);
i++;
head_node = head_node->next;
}
printf("%d---%d\n", i, head_node->data);
}
int game_start(Node *head_node, int rad,int people_num)
{
Node *p = head_node;
Node *s = p;
int len = people_num;
while(len != 1)
{
for (int i=0; i<rad-1; i++)
{
p = p->next;
}
s = p;
p->prev->next = p->next;
p->next->prev = p->prev;
p = p->next;
printf("%d ",s->data);
free(s);
len--;
}
int x = p->data;
free(p);
return x;
}
Node *create_ring(int peopel_num)
{
Node *head_node = NULL;
Node *p;
for (int i=0; i<peopel_num; i++)
{
p = create();
p->data = i+1;//使其从1开始
insert_tail(&head_node, p);
}
p = head_node;
while (p->next != NULL)
{
p = p->next;
}
p->next = head_node;
head_node->prev = p;
return head_node;
}
双向链表实现约瑟夫环
最新推荐文章于 2021-04-23 11:10:33 发布