【C++】约瑟夫环(数组+链表)

基于数组:

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std; int *a;
int *vis; bool isfull(int m)
{
for(int i=;i<m;i++)
{
if(!vis[i])
return false;
}
return true;
} void john(int m,int n)
{
int p=m-;
while(!isfull(m))
{
int left=n;
while(left>)
{
p=(p+)%m;
if(!vis[p])
{
left--;
}
cout<<vis[p];
}
vis[p]=;
cout<<":"<<a[p]<<endl;
}
} int main()
{
int m,n;
while(scanf("%d %d",&m,&n)&&m&&n)
{
a=(int *)malloc(m*sizeof(int));
for(int i=;i<m;i++)
a[i]=i+;
vis=(int *)malloc(m*sizeof(int));
for(int i=;i<m;i++)
vis[i]=; john(m,n);
} return ;
}

基于链表:

#include<iostream>
using namespace std; struct node
{
int data;
node *next;
}; node *head; void john(int m,int n)
{
node *p=head;
node *r=head->next;
while(r->next!=head)
r=r->next;
while(p)
{
if(p->next==p)
{
cout<<p->data<<endl;
return ;
}
int left=n;
while(left>)
{
left--;
p=p->next;
r=r->next;
}
cout<<p->data<<endl;
r->next=p->next;
delete p;
p=r->next;
}
} int main()
{
int m,n;
while(scanf("%d %d",&m,&n)&&m&&n)
{
head=new node();
head->data=;
node *p=head;
int a=;
while(a<=m)
{
node *t=new node();
t->data=a;
p->next=t;
p=p->next;
a++;
}
p->next=head;//形成环
/*
p=head->next;
while(p!=head)
{
cout<<p->data<<endl;
p=p->next;
}
*/
john(m,n);
} return ;
}

运行示例:

【C++】约瑟夫环(数组+链表)

tz@HZAU

2019/3/12

上一篇:啰嗦的 java,简洁的 lombok —— lombok 的使用及简单实现单例模式注解


下一篇:根据PDF模板生成PDF文件(基于iTextSharp)