Algorithm One Day One--ジョセフリング(ハンカチの問題)


アルゴリズムはプログラミングの魂であり、プログラミング思想の精髄である--Algorithm One Day One
/******************************************************************** 
created:2015 1 20  23:06:46    
author: Jackery     
purpose: Joseph problem 
*********************************************************************/  
#include"stdafx.h"
#include<iostream>
using namespace std;

typedef struct _Node
{
	int data;
	struct _Node*next;
} node_t;

typedef struct _Linklist
{
	node_t*phead;
	node_t*ptail;
	int len;
}Linklist;
static node_t*GetNode(int i )//        
{
	node_t*pNode;
	pNode=new node_t;
	if(!pNode)
	{
		cout <<"      " <<endl;
		exit(-1);
	}
	pNode->data=i;
	pNode->next=NULL;
	return pNode;
	delete pNode;
}
void init_list(Linklist*plist)//              
{
	node_t*p;
	p=GetNode(1);
	//printf("TheNewNodeis:%d
",p->data);//****TEST**** 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); /********TEST******** cout <<"The New Node is:" <<pNew->data << endl; ********TEST********/ plist->ptail->next=pNew; plist->ptail=pNew; pNew->next=plist->phead; plist->len++; } } // // void Print_List(Linklist*plist) // { // node_t*pCur=plist->phead; // do // { // cout << "The "<< pCur->data <<"person." <<endl; // pCur=pCur->next; // }while(pCur!=plist->phead); // cout << "The length of the List "<< plist->len<< endl;; // } //Joseph function implement void joseph(Linklist* plist,int m,int k) { node_t *pPre=plist->ptail; node_t *pCur=plist->phead; int i,j; cout << " : "<< endl; while(plist->len != 1) { i=0; j=0; while(j<k-1) { pPre=pPre->next; j++; } while(i< m -1) { pPre=pPre->next; i++; } pCur=pPre->next; int temp=pCur->data; cout <<" " << temp << " "<< endl ; pPre->next=pCur->next; free(pCur); plist->len--; } cout <<" " << pPre->data << " " << endl; ; cout << "The last one is:" << pPre->data<< endl; } int main(int argc, char * argv[]) { int n=0; cout <<" : "<<endl;; cin >> n; int m=0; cout << " m , "<<endl; int k; cin >> k; cout << " k " << endl; cin >>m; Linklist pList; init_list(&pList); Create_List(&pList,n); // Print_List(&pList); joseph(&pList,m,k); return 0; }