圆桌问题

来源:互联网 发布:鹿铃动画片 知乎 编辑:程序博客网 时间:2024/04/30 01:16

有n个人坐在一个圆桌上,从第k个人开始报数,报到第m个数时,此人离开圆桌,继续从下一个人开始报数,直到桌上的人都离开为止。

:使用循环链表实现。

#include<iostream>#include<string>using namespace std;class dll{public:dll():data(0),prev(NULL),next(NULL){}int data;dll *prev;dll *next;};dll* del(dll *p){dll *temp;temp=p->next;cout<<p->data<<endl;p->prev->next=p->next;p->next->prev=p->prev;delete p;return temp;}int main(){int n=10,m=1,k=2;//共有n个数,从第k个数开始,每m个数输出一个数。dll *head=new dll[1];cin>>head->data;head->next=head;head->prev=head;dll *p1=head,*p2;for(int i=1;i<n;i++){p2=new dll[1];cin>>p2->data;p2->prev=p1;p1->next=p2;p1=p2;}p2->next=head;head->prev=p2;p1=head;for(int j=1;j<=15;j++){cout<<p1->data;p1=p1->next;}cout<<endl;p1=head;for(int l=1;l<k;l++)p1=p1->next;while(p1->next!=p1){for(int j=1;j<m;j++){p1=p1->next;}p1=del(p1);}del(p1);}


原创粉丝点击