数据结构与算法MOOC / 第2周 线性表(Linear Lists)1:约瑟夫问题

来源:互联网 发布:vscode md预览 编辑:程序博客网 时间:2024/05/17 02:34
总时间限制: 
1000ms 
内存限制: 
65536kB
描述

有n只猴子,按顺时针方向围成一圈选大王(编号从1到n),从第1号开始报数,一直数到m,数到m的猴子退出圈外,剩下的猴子再接着从1开始报数。就这样,直到圈内只剩下一只猴子时,这个猴子就是猴王,编程求输入n,m后,输出最后猴王的编号。

输入
输入包含两个整数,第一个是n,第二个是m (0 < m,n <=300)。
输出
输出包含一行,即最后猴王的编号。
样例输入
12 4
样例输出
1
要注意头尾相连,就不存在头,尾,创建一开始就要头尾相连
#include<stdio.h>#include<stdlib.h>struct node{int num;struct node *next;};int n,m;struct node *creat(void){struct node *head,*p1,*p2;head=NULL;int i=0;for(i=1;i<=n;i++){p1=(struct node*)malloc(sizeof(struct node));p1->num=i;if(head==NULL)head=p1;elsep2->next=p1;p2=p1;}p1->next=head;return head;}struct node *del(struct node *head){int f=1;struct node *p1,*p2;p1=head;while(p1!=p1->next){if(f==m){p2->next=p1->next;f=1;}else{p2=p1;f++;}p1=p1->next;}return p1;}void print(struct node *head){printf("%d\n",head->num);}int main(){struct node *head;scanf("%d%d",&n,&m);head=creat();head=del(head);print(head);return 0;}

0 0