本人闲暇时间编的一个求解约瑟夫环的程序
#include<malloc.h>#define LEN sizeof(struct linklist)
struct linklist
{int data;
struct linklist *next;
};
int N,M,Length,j,k,i,a,H,t;
main()
{struct linklist * head;
struct linklist * create();
printf("请输入总数 N:\n");
scanf("%d",&N);
printf("请输入开始的号码 H:\n");
scanf("%d",&H);
printf("请输入结束号码 M:\n");
scanf("%d",&M);
Length=N;
head=create();
print(head);
}
struct linklist * create()
{struct linklist *head;
struct linklist *p;
struct linklist *q;
head=(struct linklist * )malloc(LEN);
head->data=1;
q=(struct linklist * )malloc(LEN);
q->data=N;
head->next=q;
q->next=head;
for(i=N-1;i>1;i--)
{p=(struct linklist * )malloc(LEN);
p->data=i; p->next=head->next; head->next=p;
}
return(head);
}
print(struct linklist *head)
{struct linklist *p;
struct linklist *p1,*p2,*p3;
a=1;
printf("输出结果如下:\n\n");
if(M==1 && H==1)
{p2=head->next;
while(p2->next!=head) p2=p2->next;
while(p2->next!=p2)
{ printf("%-6d ",p2->next->data); p3=p2->next;
p2->next=p2->next->next; free(p3); }
printf("%-6d ",p2->data); free(p2) ;
}
else
{ p=head;p1=p;
for(t=1;t<=H-1;t++)
{p=p->next;p1=p;}
for(k=1;k<=Length;Length--)
{for(j=1;j<M;j++)
{p1=p;
p=p->next;
}
printf("%-6d ",p->data);
a=a+1;
if(a>10)
{ printf("\n");
a=1;}
p1->next=p->next; free(p); p=p1->next;
}
}
}
[[it] 本帖最后由 编程游侠 于 2008-4-20 20:13 编辑 [/it]]