很经典的数据结构

1.Numbered 1, 2,... N n individuals sitting around a circle, contract number is k (1 < = k < = n), people started to count off from 1 to m the man out, it's the next and started to count off from 1, count to m the dequeue and so on, until all out, creating a team number sequence.

/*
* funtion: Josephu
* parameter:
* @ the number of circle
* @ the interval No
* return value: the winer number
*/
/*eg1 :With an array of implementation */
int  josephu(int n,int m)
{
	int i,j = 0;
	int flag;
	int buff[N];
	int *buff = (int *)malloc(n * sizeof(int)) ;
	for(i = 0;i < N; i++)
	buff[i] = 1;
	
	for(i = 1; i < n; i++)
	{
		flag = 0;
		if(j == n) j = 0;
		while(flag < m)
		{
			if(buff[j])
				flag ++;
			j ++ ;
		}
		buff[j - 1] = 0;
		printf("the %dth man is exit,the no is %d\n",i,j);
	}
	free(buff);
	return  j;
}


/*eg2 :Implemented with a linked list */
typedef   int    Datatype;
typedef struct _LinkNode_{
	struct _Linknode_ *next;
	Datatype index;
}Linknode;

Linknode *createlinknode()
{
	Linknode *head = (Linknode *)malloc(sizeof(Linknode));
	head->next = NULL;
	return head;
}

int josephu_algorithm(int n,int m)
{
	LinkNode *head,tail;
	int i,j;
	
	head = createlinknode();
	tail = head;
	for(i = 1 ; i < n ; i++ )
	{
		tail->index = i
		tail->next = createlinknode();
	}
	tail->index = i;
	tail->next = head;  //Buid two-way linked list
	
	for(i = 1; tail != head ; i++)
	{
		for(j = 1; j < m; j ++)
		{
			tail = head;
			head = head->next;
	    }
		tail->next = head->next;
		free(head);
		head = tail->next;
		printf("the %dth man is exit,the no is %d\n",i,j);
	}
	i = head->index;
	free(head);
	return i;
}
int main()
{
int n, m;scanf("%d%d", &n, &m);
printf("the final champion is %d\n", Josephu(n, m));
return 0;
}
2. How to to achieve the above functions without using recursive calls?
//Fibonacci ratched series recursive implementation method is as follows:
int Funct(int n)
{
	if(n == 0) return 0;
	if(n == 1) return 1;
	return Funct(n) + Funct(n-1);
}
//

/*
* funtion: Fibonacci ratched series 
* parameter:
* @ the Natural number 
* return value: Fibonacci ratched series 
*/
*  Function: Fibonacci ratched series
*  parameter:
*  @ Natural numbers
*  @ return value :The nth Fibonacci number
*/
int Funct(int n)
{
	int a=0,b=1,c;
	
	if(n == 0 || n == 1) c = 1;
	else
	{
	for(i = 2; i < n;i++)
	{
		c = a + b;
		a = b;
		b = c;
	}
	return c;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值