用数组和链表实现约瑟夫环问题

数组实现:

#include

using namespace std;
int main()
{
int n,m,s,i=0,j=0,k=0;
cout<<"please input the length of the array:";
    cin>>n;
cout<<"please input the number of output:";
cin>>m;
int *a=new int[n];
for(i=0;i
a[i]=i+1;
for(i=0;i
{
    if(i==n)          //make the array like a circle so that to continue easily 
     i=0;
if(a[i]>0)
{
j++;          //count all the effective values
    if(j%3==0)
{
    cout<<a[i]<<" ";     //output the value required
      a[i]=0;
}
}
s=0;
for(k=0;k
s+=a[k];
    if(s==0)                   //count values in the array to guarantee all value has been out
break;                 //out of the loop
}
return 0;

}

链表实现:

#include
using namespace std;
struct ele{
int num;
struct ele * next;
}
main()
{
int n,m,i;
struct ele *h,*u,*p;
cout<<"cin n and m:";
cin>>n>>m;
h=u=new struct ele[];
h->num=1;
for(i=1;i
{
u->next=new struct ele[];
u=u->next;
u->num=i+1;
}
u->next=h;            //链表首尾相连
while(n)
{
for(i=1;i
u=u->next;
p=u->next;
cout<<p->num<<" ";
u->next=p->next;     //删去节点p
// delete p;           //为什么错误出在这里??
--n;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值