约瑟夫环

57 篇文章 3 订阅

参考:

http://zh.wikipedia.org/wiki/%E7%BA%A6%E7%91%9F%E5%A4%AB%E6%96%AF%E9%97%AE%E9%A2%98

http://mathworld.wolfram.com/JosephusProblem.html

source code:http://baike.baidu.com/view/717633.htm

【摘自百度】:

约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。



我的注释版本:

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

struct _Node {
	int data;
	struct _Node *next;//自引用结构
};

typedef struct _Node node_t; //typedef : 给 struct _Node 这个结构体赋予名字 node_t(现在,node_t就类似于int)

typedef struct _Linklist {
	node_t *phead;//结构体嵌套
	node_t *ptail;
	int len;
} Linklist;

static node_t *GetNode(int i)
{
	node_t *pNode; // pNode 是指向结构体node_t的指针
	pNode = (node_t*) malloc(sizeof(node_t));//给node_t结构体动态分配内存,在malloc成功后返回一个node_t类型的指针
	if (!pNode) {
		printf("Error,the memory is not enough!\n");
		exit(-1);
	}
	pNode->data = i; //指向结构体的指针通过-> 引用结构体成员
	pNode->next = NULL;
	return pNode;
}

void init_list(Linklist *plist)
{
	node_t *p;
	p = GetNode(1); // 用第一个节点初始化循环单链表
	plist->phead = p;
	plist->ptail = p;	//构造循环链表
	p->next = plist->phead;
	plist->len = 1;
}

static void Create_List(Linklist *plist, int n)  // 把其余数据添加到循环单链表中
{
	int i = 0;
	node_t *pNew;
	for (i = 2; i <= n; i++) {
		pNew = GetNode(i);
		plist->ptail->next = pNew;
		plist->ptail = pNew;
		pNew->next = plist->phead;
		plist->len ++;
	}
	printf("Finish!\n");
}

void Print_List(Linklist *plist)
{
	node_t *pCur = plist->phead;
	do {
		printf("The %d person.\n", pCur->data);
		pCur = pCur->next;
	} while (pCur != plist->phead);
	printf("The length of the List: %d\n", plist->len);
}

void joseph(Linklist *plist, int m)    //约瑟夫回环函数实现
{
	node_t *pPre = plist->ptail;
	node_t *pCur = plist->phead;
	int i;
	while (plist->len != 1) {
		i = 0;
		while (i < m - 1) {
			pPre = pPre->next;
			i++;
		}
		pCur = pPre->next;
		pPre->next = pCur->next;
		printf("%2d was killed !\n",pCur->data);//打印每次被kill的人
		free(pCur);
		plist->len--;
	}
	printf("The last one is: %d\n", pPre->data);
}
int main() {
	int m,n;
	printf("Please input the Length of the Circle list: ");
	scanf("%d", &n);
	printf("Please input the Stop point: ");
	scanf("%d", &m);
	Linklist pList;
	init_list(&pList);
	Create_List(&pList, n);
	Print_List(&pList);
	joseph(&pList, m);
	return 0;
}


  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值