数据结构与算法分析3.10
来源:互联网 发布:元数据 数据元 编辑:程序博客网 时间:2024/06/03 08:51
/*Josephus 问题 N个人从1到N编号,围坐成一个圆圈。从1号开始传递一个热土豆。经过M次传递后拿着热土豆的人被清除离座,围坐的圆圈缩紧,由坐在被清除的人后面的人拿起热土豆继续进行游戏,最后剩下的人取胜*/
//头文件
#ifndef _Josephus_H
typedef struct Node *PtrToNode;
typedef PtrToNode Position;
typedef PtrToNode List;
Position CreatRingList(int n);
void PrintList(Position phead);
int Winner(Position phead,int n,int m);
#endif
#include <stdio.h>
#include "josephus.h"#include <stdlib.h>
struct Node{
int element;
Position next;
};
// 循环链表
{
int i;
Position head,p,tail;
List L;
L=(List)malloc(sizeof(struct Node));
if(L==NULL)
{
printf("error");
return NULL;
}
head=L;
head->element=1;
head->next=head;
tail=head;
for(i=2;i<=n;i++)
{
p=(Position)malloc(sizeof(struct Node));
if(L==NULL)
{
printf("error");
return NULL;
}
p->element=i;
tail->next=p;
p->next=head;
tail=p;
}
return head;
}
void PrintList(Position phead)
{
Position p=phead;
while(p->next!=phead)
{
printf("%d",p->element);
p=p->next;
}
printf("%d",p->element);
}
//返回获胜的序号
{
int i,j;
Position p,q;
p=phead;
//printf("%d",p->element);
if(m==0)
return phead->element;
/*外循环:n个数,最后剩下一个,删除n-1个,即循环n-1次。内循环:每向后m次,删除一项,循环m次。
内循环:p指针为开始位置,p指针向后移动,q记录p的前一项。当移动m次时,开始删除操作。
删除操作:q的下一项为p-next,p所指项被删除,p重新赋值为删除项的后一项,即q->next。
重新开始删除操作。直到剩下一个为止*/
for(i=1;i<n;i++)
{
for(j=1;j<=m;j++)
{
q=p;
p=p->next;
}
q->next=p->next;
//printf("%d",p->element);
free(p);
p=q->next;
}
return p->element;
}
main()
{
int winnernum;
Position phead;
phead=CreatRingList(5);
//PrintList(phead);
winnernum=Winner(phead,5,3);
printf("the winner is %d",winnernum);
}
阅读全文
0 0
- 数据结构与算法分析3.10
- 数据结构算法与分析
- 数据结构与算法分析
- 数据结构与算法分析
- 数据结构与算法分析
- 数据结构与算法分析
- 数据结构与算法分析
- 数据结构与算法分析
- 数据结构与算法分析
- 《数据结构与算法分析》
- 数据结构与算法分析c++:算法分析
- 数据结构与算法分析c++:算法分析
- 数据结构与算法分析P241T4
- 数据结构与算法分析 感悟
- 数据结构与算法分析 树
- 《数据结构与算法分析》Chap3
- 《数据结构与算法分析》Chap4
- 数据结构与算法分析-表
- __read_mostly的使用
- NEW DAY!
- TabLayout和ViewPager基础使用
- [收藏]spring、spring-mvc、spring-boot学习教程
- 男子44年前1200元存款相当 30万,今日银行只给2600块
- 数据结构与算法分析3.10
- c++ 内联函数 (讲解的TM真好)
- BST的基本操作
- C#使用Interlocked进行原子操作
- Faster-RCNN下Caffe安装笔记
- android_跳转WebView
- 转载-3分钟了解入门「机器学习」该学习什么?(下)
- nginx代理,Java获取访问url
- 苹果公司对失败的总结和展望未来