啰嗦的约瑟夫问题
2016-01-03 17:24
204 查看
#include<stdio.h>
#include<malloc.h>
#define Len sizeof(struct node)
struct node
{
int num;
struct node*next;
};
struct node* create(int m) //建立循环链表
{
struct node*head,*p1,*p2;
int i;
for(i=1;i<=m;i++)
{
if(i==1)
{
head=p2=(struct node*)malloc(Len);
p2->num=1;
}
else
{
p1=(struct node*)malloc(Len);
p1->num=i;
p2->next=p1;
p2=p1;
}
}
p1->next=head;
return head;
}
void print(struct node*head) // 打印循环链表
{
struct node*p=head;
do
{
printf("%4d",p->num);
p=p->next;
}
while(p!=head);
}
struct node* kill(int n,struct node*p1) //一次杀一个,要求输入n和起始地址
{
int i;
struct node*p2;
for(i=1;i<=n;i++)
{
if(i==n)
{
p2->next=p1->next;
return(p1->next);
}
else
{
p2=p1;
p1=p1->next;
}
}
}
int flag(int n,struct node*survivor) //确认幸存者的人数够不够一次循环
{
struct node*p1;
int i;
p1=survivor;
for(i=1;i<=n;i++)
{
p1=p1->next;
}
if(p1==survivor)return 1;
else return 0;
}
void main()
{
int m,n,f=0;
struct node*head,*survivor;
scanf("%d,%d",&m,&n);
head=create(m);
/*print(head);
printf("\n");*/
survivor=head;
while(f==0)
{
f=flag(n,survivor);
survivor=kill(n,survivor);
//print(survivor);
//printf("\n");
}
print(survivor);
printf("\n");
}
#include<malloc.h>
#define Len sizeof(struct node)
struct node
{
int num;
struct node*next;
};
struct node* create(int m) //建立循环链表
{
struct node*head,*p1,*p2;
int i;
for(i=1;i<=m;i++)
{
if(i==1)
{
head=p2=(struct node*)malloc(Len);
p2->num=1;
}
else
{
p1=(struct node*)malloc(Len);
p1->num=i;
p2->next=p1;
p2=p1;
}
}
p1->next=head;
return head;
}
void print(struct node*head) // 打印循环链表
{
struct node*p=head;
do
{
printf("%4d",p->num);
p=p->next;
}
while(p!=head);
}
struct node* kill(int n,struct node*p1) //一次杀一个,要求输入n和起始地址
{
int i;
struct node*p2;
for(i=1;i<=n;i++)
{
if(i==n)
{
p2->next=p1->next;
return(p1->next);
}
else
{
p2=p1;
p1=p1->next;
}
}
}
int flag(int n,struct node*survivor) //确认幸存者的人数够不够一次循环
{
struct node*p1;
int i;
p1=survivor;
for(i=1;i<=n;i++)
{
p1=p1->next;
}
if(p1==survivor)return 1;
else return 0;
}
void main()
{
int m,n,f=0;
struct node*head,*survivor;
scanf("%d,%d",&m,&n);
head=create(m);
/*print(head);
printf("\n");*/
survivor=head;
while(f==0)
{
f=flag(n,survivor);
survivor=kill(n,survivor);
//print(survivor);
//printf("\n");
}
print(survivor);
printf("\n");
}
相关文章推荐
- Linux 命令
- Java中的构造方法总结
- 最小生成树专题
- 怎样获取浏览器上次的会话数据(session)
- React 根据官方总结的规范
- To Learn
- 蓝桥杯 历届试题 核桃的数量(求三个数的最小公倍数)
- linq to sql 提高性能的5种方式
- 微信公众平台开发 OAuth2.0网页授权认证
- HTML学习笔记——各种居中对齐
- LeetCode - Maximal Rectangle
- leetcode第9题——*Palindrome Number
- George and Sleep
- view的封装,xib和stroryBoard加载及使用
- 学过JDBC才知道前一篇文章的经历完全可以避免。。。
- CentOS7中自编的一个支持suid的system函数(c语言)
- Python—装饰器
- String类之indexOf--->查找某字对应的位置
- FPGA笔记 AS和JTAG下载方式区别
- java学习细节知识点总结