循环链表实现约瑟夫环

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

 

 

  1. #include<iostream>
  2. #include<malloc.h>
  3. #include<stdlib.h>
  4. using namespace std;
  5. #define OK 1
  6. #define ERROR 0
  7. #define MAXSIZE 10
  8. typedef int Status;
  9. typedef int ElemType; 
  10. typedef struct CircularList
  11. ElemType data; 
  12. struct CircularList *next; 
  13. }CircularList,*LinkList; 
  14. Status Init_List(LinkList &L,int n)          //建立无头结点单循环链表 
  15. {
  16.     if(n<1) return ERROR;
  17.     L=(LinkList)malloc(sizeof(CircularList));
  18.     L->data=1;
  19.     if(n==1) {L->next=L; return OK;} 
  20.     int i;
  21.     LinkList p,q;
  22.     for(i=2;i<=n;i++)
  23.     {
  24.             p=(LinkList)malloc(sizeof(CircularList)) ;
  25.             p->data=i;
  26.             if(i==2) {L->next=p; q=p;}
  27.             else  {q->next=p;q=p;}
  28.             }
  29.     p->next=L;
  30.     return OK;       
  31.        }
  32. Status Delete_List(LinkList &L)         //删除L的下一节点 
  33. {
  34.      LinkList p=L->next;
  35.      if(p==L) return ERROR;
  36.      L->next=p->next;
  37.      free(p);
  38.      return OK;  }
  39.        
  40. void JOSEPHUS(int n,int k,int m) 
  41. {//n为总人数,k为第一个开始报数的人,m为出列者喊到的数
  42.      LinkList L;
  43.      Init_List(L,n);
  44.      for(int i=1;i<k;i++)
  45.          L=L->next;
  46.      int flag=1;
  47.      while(flag)
  48.      {
  49.         for(int i=1;i<m-1;i++)
  50.             L=L->next;
  51.         flag=Delete_List(L);
  52.         L=L->next;
  53.      }
  54.      cout<<"The end:"<<L->data<<endl;
  55.      }
  56.      
  57. int main()
  58. {
  59.     int n,k,m;
  60.     while(cin>>n>>k>>m)
  61.     JOSEPHUS(n,k,m);
  62.     return 0;}
  63. 1 1 1
  64. The end:1
  65. 5 2 3
  66. The end:5
  67. 8 5 3
  68. The end:3
  69. 8 1 3
  70. The end:7
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值