循环链表中约瑟夫环的问题

来源:互联网 发布:emui 知乎 编辑:程序博客网 时间:2024/05/16 11:01

在程序员面试宝典中,有道面试题如下:

已知n个人(以编号1,2,3,,...,n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;从他的下个开始,数到k重新数数,数m个数,那个人出列;以此重复下去,直到圆桌周围的人全部出列。试用C++编程实现。

#include <iostream>using namespace std;struct node{int data;node* next;};void fun(int n,int m,int k){node* head,*p1,*p2,*first,*second;int m1,k1;head=(node*)malloc(sizeof(node));head->data=1;p1=head;for(int i=2;i<=n;i++){p2=(node*)malloc(sizeof(node));p2->data=i;p1->next=p2;p1=p2;}p1->next=head;first=head;while(n--){   m1=m;   k1=k;   while(k1-1)   {second=first;first=first->next;--k1;   }//找到首先开始报数的位置;   while(m1-1)   {second=first;first=first->next;--m1;   }   second->next=first->next;   printf("%d->",first->data);   free(first);   first=second->next;}}int main(){fun(13,4,1);}


0 0