3 1 #include
#include
struct Node
{
int nSecret ;
int nId ;
Node *pNext ;
} ;
Node *g_pHeader = NULL ;
int main()
{
int M , ns , nCount = 0 , id = 0;
bool bHeader = false ;
// input process ...
printf(" please input the maxmmum value of M : ");
scanf("%d",&M) ;
printf(" please input the secret id and zero over : " ) ;
Node *p = NULL , *last = NULL ;
while( scanf("%d",&ns) && ns != 0 )
{
id++ ;
Node *q = new Node ; // malloc( sizeof( Node ) ) ...
q->nSecret = ns ;
q->nId = id ;
if( !bHeader )
{
bHeader = true ;
p = g_pHeader = q ;
p->pNext = g_pHeader ;
}
else
{
p->pNext = q ;
p = q ;
p->pNext = g_pHeader ;
}
}
// dispose process ...
last = p ; // 最后一个
p = g_pHeader ; // 第一个
while( p != NULL )
{
nCount++ ;
if( last == p )
{
printf("%-4d", p->nId ) ;
delete p ; // free(p)
break ;
}
else if( nCount % M == 0 )
{
// 删除p
M = p->nSecret ;
last->pNext = p->pNext ;
printf("%-4d", p->nId ) ;
delete p ;
p = last->pNext ;
nCount = 0 ;
}
else
{
last = p ;
p = p->pNext ;
}
}
return 0 ;
}
#include
#include
typedef struct people
{
int num;
int code;
struct people *next;
}*LinkPtr, Node, *NodePtr;
//创建链表
LinkPtr createLink(int p_num)
{
int i;
LinkPtr head;
NodePtr p;
//头结点
head=(NodePtr)malloc(sizeof(Node));
p=head;
//创建结点,并输入密码
for(i=1; i<=p_num; i++)
{
p->next = (NodePtr)malloc(sizeof(Node));
p=p->next;
p->num = i;
printf("\n输入编号%d密码:",i);
scanf("%d",&p->code);
}
//链表成环
p->next = head->next;
return head;
}
//T除报到m值的人,并按其密码修改m值
void deleteNode(NodePtr p, NodePtr q, int *m)
{
q->next = p->next;
*m = p->code;
printf("%d ",p->num);
free(p);
p=NULL;
}
void josphGame(LinkPtr head, int m)
{
NodePtr p,q;
int i=0;
int j=0;
int record = 0;
p = head;
while(1)
{
//判断游戏是否结束,即所有人出局
if(p->next==p)
{
printf("%d ",p->num);
break;
}
//报数
for(i=0;i
q=p;
p=p->next;
}
//T除报到m数的人
deleteNode(p,q,&m);
p=q;
}
}
void main()
{
int m = 0;
int p_num;
LinkPtr head=NULL;
printf("输入m值:");
scanf("%d",&m);
printf("输入人数:");
scanf("%d", &p_num);
head = createLink(p_num);
printf("输出编号:\n");
//游戏开始运行
josphGame(head,m);
printf("\n");
system("PAUSE");
}
运行结果:
输入m值:20
输入人数:7
输入编号1密码:3
输入编号2密码:1
输入编号3密码:7
输入编号4密码:2
输入编号5密码:4
输入编号6密码:8
输入编号7密码:4
输出编号:
6 1 4 7 2 3 5
写完了..花了一个多小时- -实力不行啊
怎么会有这么多约瑟夫问题
晚点打给你啊,太长了