1. 程式人生 > >c語言實現約瑟夫環-每隔幾個刪除一個,求剩下的

c語言實現約瑟夫環-每隔幾個刪除一個,求剩下的

c語言連結串列實現約瑟夫環的程式碼,每隔任意元素刪除一個,逐步輸出各個刪除元素

#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define N 10
struct lnode
{
int i;
struct lnode *next;
  
};
 void cutoff(struct lnode *head, int n, int total)
 {
struct lnode *pp,*qq=head;
int i;
     if(total==0)
return ;
n=n%total;
if(n==0)
n=total;
for(i=0; i<n; i++)
{    pp=qq;
    qq=qq->next;
}
pp->next=qq->next;
printf("%d  ",qq->i );
free(qq);
    cutoff(pp,n,total-1);
 }
int main(void)
{  
 struct lnode *head,*p1,*p2;
 int m,n;
 head=NULL;
   for(int i=0; i<10; i++)
{
p1=(struct lnode*)malloc(sizeof(struct lnode));
puts("輸入一個數組中的值:");
scanf("%d",&m);
p1->i=m;


if(head==NULL)
{
 head=p1;
 p2=p1;
}
else 
{
p2->next=p1;
p2=p1;
}

   }
   p2->next=head;
   puts("每隔幾個數刪除一個?:");
  scanf("%d",&n);
int h=10; 
   cutoff(p2,n,h);
return 0;


}

以上是連結串列實現方法,下面是陣列實現的方法

#include<stdio.h>


void main()
{
int a[50];
int i,n,k,m;
scanf("%d",&n);
    for(i=0;i<n;i++)
a[i]=i+1;
     k=0;
     m=0;
i=0;
while(m<n-1)
{

if(a[i]!=0)  k++;
if(k==3)
{
//printf("%d \n",a[i]);
//for(int j=0;j<=n-1;j++)
//printf("%d ",a[j]);
a[i]=0;
k=0;
m++;
}
i++;
if(i==n)  i=0;

}
  for(i=0;i<n;i++)
 if(a[i]!=0)
 printf("最後一個編號為:%d ",a[i]);

}