首先,我们需要知道什么是约瑟夫环?
其本质就是将一个链表首尾相连,形如一个环罢了。
接下来我简单的来写下伪代码:
创建结构体
struct
{ num;
next;
}
一个初始化函数init;
一个遍历函数;
一个插入函数(这里有一个尾插和首插,这里用尾插相对简单;只需要让前一个的next指向下一个结点即可!)
一个删除函数(我们需要知道它的编号)r然后将其free掉就删掉了;
话不多说直接上代码:
#include<stdio.h>
#include<string.h>
using namespace std;
#include<malloc.h>
typedef struct Node
{
int Num;
struct Node *next;
}JoseNode,*PNode,*HNode;
/********************************/
int JoseInit(HNode * h)
{
if (!h)
{
printf("init error! \n");
return 0;
}
(*h)->next = (*h);
return 1;
}
/***********************************/
int JoseInsert(JoseNode *h, int pos, int x)
{
PNode p = h,q;
int i =1;
if (pos == 1)
{
p->Num = x;
p->next = p;
return 1;
}
while (i <pos-1)
{
p = p->next;
i++;
}
q = (PNode)malloc(sizeof(JoseNode));
q->Num =x;
q->next =p ->next;
p->next = q;
return 1;
}
/**************************************/
int JoseDelete(HNode h, int M, int k)
{
int i = 1 ;
PNode p = h,q;
while(M>1)
{
for(i =1;i<k-1;i++)
{
p= p -> next;
}
q = p->next;
p->next = q->next;
printf("the get out people is :%d number\n",q->Num);
free(q);
p= p->next;
M--;
}
printf ("the last winner is:%d numebr!");
return 1;
}
/********************************************/
int TraverseList(HNode h, int M)
{
int i ;
PNode p = h;
printf("the all join numbers are : \n");
while (i<M)
{
printf("%d\t",p->Num);
p = p->next;
i++;
}
printf("\n");
return 1;
}
int main()
{
int i;
int N;
int k;
printf("please input people:");
scanf("%d",&N);
printf("please input login passward:");
scanf("%d",&k);
HNode h = ((HNode )malloc(sizeof(JoseNode)));
JoseInit(&h);
for (i =1 ; i <= N; i++)
{
JoseInsert(h,i,i);
}
TraverseList(h,N);
if(k > 1)
JoseDelete(h,N,k);
else
{
for (i = 1; i<N;i++)
printf("get out : %d \n",i);
printf("winner belongs to :%d");
}
printf("****************************\n");
return 0;
}