双向链表实现约瑟夫环

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值