本程序用顺序表实现,相对复杂一点了
#include
#include
#include
#define ok 1
#define error 0
#define overflow -2
typedef int status;
typedef struct node{
int number;
int password;
}node;
typedef struct sqlist{
node *elem;
int length;
int listsize;
}sqlist;
void initlist(sqlist &l,int n) /* 初始化函数*/
{ int i; node *newbase;
newbase=(node *)malloc(n*sizeof(node));
if(!newbase) exit(overflow);
l.elem=newbase;
printf("Input %d password.\n",n);
for(i=0;i
l.elem[i].number=i+1;
}
l.length=l.listsize=n;
}
status delete_sqlist(sqlist &l,int i,int &e) // 删处给定位置的元素
{ node *p,*q;
if((i<1)||(i>l.length))
return error;
q=&(l.elem[i-1]);
e=q->password;
printf("%d ",q->number);
p=l.elem+l.length-1;
for(q;q<=p;++q)
*(q)=*(q+1);
--l.length;
return ok;
}
void chang_sqlist(sqlist &l,int t) /*将顺序表中的元素循环向左移动*/
{ int i,j;
node value;
for(i=t;i<=l.length;i++)
{ j=i-1;
while(j>i-t)
{ value=l.elem[j];
l.elem[j]=l.elem[j-1];
l.elem[j-1]=value;
j--;
}
}
}
void sort_list(sqlist &l,int m) /* 主算法函数*/
{ int t,delete_pos=1;
printf("The result:\n");
while(l.length>=1)
{ t=m%l.length;
t=(t==0)?l.length:t;
delete_sqlist(l,t,m);
chang_sqlist(l,t);
}
putchar('\n');
}
void main()
{ int n,m;
sqlist l;
printf("Input the number of persons.\nn=");
do{scanf("%d",&n);
if(!n) printf("Input error!\n");
}while(!n);
initlist(l,n);
printf("Input the limit.\nm=");
scanf("%d",&m);
sort_list(l,m);
getch();
}
正文
约瑟夫环程序(顺序实现)2005-05-03 22:48:00
【评论】 【打印】 【字体:大 中 小】 本文链接:http://blog.pfan.cn/super/848.html
阅读(4249) | 评论(1)
版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!
评论