ジョセフリングの実装−チェーンテーブル法


//最終実装方法-チェーンテーブル
#include <stdio.h>
#include <malloc.h>

struct node
{
	int nNum,nPassword;
	struct node * next;
};

typedef struct node * LNode;

LNode CreateList(const int num,const int nPwd)
{
	int i;
	LNode head = NULL,p = NULL,q = NULL;

	for(i = 1; i <= num; i ++)
	{
		p = (LNode)malloc(sizeof(struct node));
		p->nNum = i;
		p->nPassword = nPwd;

		if(NULL == head)
		{
			head = p;
		}
		else
		{
			q->next = p;
		}		
		q = p;
	}
	p->next = head;

	return p;//the previous node of the head node
}


void josephus(const int num,const int nPwd,const int nBegin)
{
	if((num <= 0) || (nPwd <= 0) || (nBegin <= 0))
	{
		return ;
	}

	LNode q = CreateList(num,nPwd);
	LNode p = q->next;

	int iNum = num,iCall = nBegin;

	while(iNum --)
	{
		for(int i  = 0;i < iCall - 1; i ++)
		{
			q = p;
			p = p->next;
		}

		q->next = p->next;
		iCall = p->nPassword;
		printf("%3d
",p->nNum); free(p); p = q->next; } } void main() { josephus(100,3,1); }
// 
#include <stdio.h>  
  
void main()  
{  
    int i,j,nNum,nDistance,nBegin;//   
  
    printf("please input nNum and nBegin:");  
  
    scanf("%d%d",&nNum,&nBegin); 
	
	if((nNum <= 0) || (nBegin <= 0))
	{
		return ;
	}
  
    int *nPassword  = new int [nNum];  
    
	int iStart = 0;//if the password must be during 1 to 24.
	while(iStart < nNum)
	{	  
		printf("the password of NO. %d is(1 ~ 24):",iStart + 1);
        scanf("%d",&nPassword[iStart]);

		if((nPassword[iStart] >= 1) && (nPassword[iStart] <= 24))
		{
			iStart ++;
		}
		else 
		{
			printf("You just input password is incorrect, please enter again!
"); } } int k = 0; nDistance = nBegin;// for(i = 0;i < nNum;i ++) { j = 1; while(j < nDistance) { while(nPassword[k] == 0) { k = (k + 1) % nNum; } j ++; k = (k + 1) % nNum; } while(nPassword[k] == 0) { k = (k + 1) % nNum; } printf("%3d
",k + 1); nDistance = nPassword[k]; nPassword[k] = 0; } }