约瑟夫环的单向循环链表的实现代码

/*************************************************************************
  > File Name: JosephCirle.c
  > Author: Wenfei6316
  > Mail: wenfei6316@163.com 
  > Created Time: 2018年06月18日 星期一 09时42分28秒
 ************************************************************************/

/*约瑟夫环说明:N(N>1) 个人组成一圈,从第 num 个人开始报数(从 1 开始报数)
 *当谁报到数字 count 时将执行枪决,然后继续从后面一位开始接着循环,
 *直到最后只剩下一个人,利用单向循环链表模拟出每次被杀的人以及最后存活的人*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum{false, true}	bool;
typedef int data_t;
typedef struct Node
{
	data_t data;
	struct Node *next;
}JosephNode, *JosephLise;

JosephLise CreateList(int num);
void PrintList(JosephLise cyclelist);
void KillGame(JosephLise cyclelist, int num, int killer);

int main(int argc, const char *argv[])
{
	int count = 10;
	int num = 8;
	int killer = 15;
	JosephLise josephcirle;
	josephcirle = CreateList(count);
	PrintList(josephcirle);

	printf("%d is beginning!\n", num);
	printf("Calling %d will be killed!\n", killer);
	KillGame(josephcirle, num, killer);

	return 0;
}

JosephLise CreateList(int num)
{
	int i;
	JosephLise p, q, s;
	if (num < 2)
	{
		printf("It is insignificance!\n");
		exit(EXIT_FAILURE);
	}
	p = (JosephLise)malloc(sizeof(JosephNode));
	if (p == NULL)
	{
		perror("Create JosephCirle failed!\n");
		exit(EXIT_FAILURE);
	}
	p->data = 1;
	p->next = NULL;
	q = p;

	for (i=2; i<=num; i++)
	{
		s = (JosephLise)malloc(sizeof(JosephNode));
		if (s == NULL)
		{
			perror("Create JosephCirle failed!\n");
			exit(EXIT_FAILURE);
		}
		s->data = i;
		q->next = s;
		q = s;
	}
	q->next = p;

	return p;
}

void PrintList(JosephLise cyclelist)
{
	bool count = false;
	JosephLise p, q;
	if (cyclelist == NULL)
	{
		printf("cyclelist is NULL!\n");
		return ;
	}
	p = cyclelist;
	while (!count)
	{
		printf("%2d  ", p->data);
		if ((p=p->next) == cyclelist)
			count = true;
	}
	printf("\n");
}

void KillGame(JosephLise cyclelist, int num, int killer)
{
	int i;
	JosephLise p, q;
	if (cyclelist == NULL)
	{
		printf("Joseph Cirle is error!\n");
		return ;
	}
	if (num<2 || killer<2)
	{
		printf("It is insignificance!\n");
		return ;
	}
	p = cyclelist;
	for (i=1; i<num-1; i++)
		p = p->next;
	while (p->next != p)
	{
		for (i=1; i<killer; i++)
			p = p->next;
		q = p->next;
		printf("%d is killed!\n", q->data);
		p->next = q->next;
		free(q);
		q = NULL;
	}
	printf("Congratulations, you are free, No%d!\n", p->data);
	free(p);

	return ;
}

    原文作者:约瑟夫环问题
    原文地址: https://blog.csdn.net/wenfei11471/article/details/80723567
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞