这个题目还是很有意思的!大一下学期学约瑟夫问题的时候,从网上找了一个别人推导出来的数学公式(真是丢脸!)自己的这个编程能力真是太渣了,惭愧呀!
今天用循环单链表解决了约瑟夫问题;这个猴子选大王的问题也就迎刃而解了!
AC代码:
#include<bits/stdc++.h>///链表法解决约瑟夫问题
using namespace std;
typedef struct node
{
int data;
node *next;
}danlist;
danlist *head;
struct node * creat(int num)
{
int i;
danlist *p,*r;
head=(struct node *)malloc(sizeof(struct node));
r=head;
for(i=0;i<num;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=i+1;
p->next=NULL;
r->next=p;
r=p;
}
p->next=head->next;
return head;
}
//void display(danlist *p)
//{
// p=p->next;
// while(p->next!=NULL)
// {
// cout<<p->data<<' ';
// p=p->next;
// }
// cout<<p->data<<endl;
//}
void xuanhou(danlist *p,int a,int b)
{
danlist *r;
r=p->next;
///int num=b-2;
///num=b;
int i;
for(i=0;i<a-1;i++)
{
for(int j=0;j<b-1;j++)
{
p=r;
r=p->next;
}
p->next=r->next;
free(r);
r=p->next;
}
cout<<p->data;
}
int main()
{
int a,b;
cin>>a>>b;
head=creat(a);
xuanhou(head,a,b);
///display(head);
return 0;
}
经典的输入,答案截屏:
知识点总结:
我要勇敢地动手去写,大胆实践;链表的知识点就那么一点!
学习心得:
十一在家有点放松,玩的时间有点多;我需要克制自己!