约瑟夫循环

        题目:n个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,每次从这个圆圈中删除第m个数字(第一个为当前数字本身,第二个为当前数字的下一个数字)。当一个数字删除后,从被删除数字的下一个继续删除第m个数字。求出在这个圆圈中剩下的最后一个数字。

       思路:创建一个循环链表,每次走m步删除一个节点,最后剩下一个 

源码:

[html]  view plain copy
  1. #include <iostream.h>  
  2. #include "malloc.h"   
  3. struct node  
  4. {  
  5.    int data;  
  6.    node *next;    
  7. };  
  8.   
  9. node *createList(int a[],int n)  
  10. {  
  11.     node *head;  
  12.     node *p,*q;  
  13.     head=(node *)malloc(sizeof(node));  
  14.     head->data=0;  
  15.     head->next=NULL;  
  16.     for(int i=0;i<n;i++)  
  17.     {  
  18.         p=(node *)malloc(sizeof(node));  
  19.         p->data=a[i];  
  20.         p->next=NULL;  
  21.           
  22.         p->next=head->next;  
  23.         head->next=p;  
  24.           
  25.     }  
  26.     q=head;  
  27.     while(q->next!=NULL)  
  28.         q=q->next;  
  29.    
  30.      q->next=head;  
  31.       
  32.           
  33.     return head;  
  34. }  
  35. void display(node *head)  
  36. {  
  37.     node *p;  
  38.     p=head;  
  39.     cout<<p->data<<endl;  
  40.     while(p->next!=head)  
  41.     {        
  42.        p=p->next;  
  43.        cout<<p->data<<endl;  
  44.     }  
  45. }  
  46. void deleteNode(node *head,int m)  
  47. {  
  48.     node *p,*q;  
  49.     p=head;  
  50.       
  51.     while(p->next!=head)//p为head前一个节点   
  52.        p=p->next;  
  53.          
  54.     while(p->next!=p)  
  55.     {  
  56.         q=p->next;  
  57.         for(int i=1;i<m;i++)//走几步   
  58.         {  
  59.             p=q;  
  60.             q=q->next;     
  61.         }  
  62.         p->next=q->next;//删除节点   
  63.         cout<<"delete node is:"<<q->data<<endl;   
  64.     }  
  65.       
  66.     cout<<"last node is:"<<p->data<<endl;   
  67. }  
  68. int main()  
  69. {  
  70.       
  71.     int a[10]={1,2,3,4,5,6,7,8,9};  
  72.     node *head;  
  73.     head=createList(a,9);  
  74.     display(head);  
  75.     //cout<<head->data;  
  76.     deleteNode(head,2);  
  77.     return 0;  
  78. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值