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

来源:互联网 发布:sip默认端口 编辑:程序博客网 时间:2024/06/05 10:18

数组实现:

#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;
}
}

原创粉丝点击