Joseph问题(循环链表)

来源:互联网 发布:斗鱼主播用的唱歌软件 编辑:程序博客网 时间:2024/05/16 09:55
Code:
  1. #include<iostream.h>   
  2.   
  3.   
  4.   
  5. struct student   
  6. {   
  7.  int rank;   
  8.  student *next;   
  9. };   
  10.   
  11.   
  12. student *final;   
  13.   
  14.   
  15. student *creat(int i)   
  16. {   
  17. student *head,*p1,*p2;   
  18. int n=1;   
  19. p1=new(student);   
  20. head=p1;   
  21. p2=p1;   
  22. p1->rank=n;   
  23. cout<<"Construct the "<<n<<"th unit"<<endl<<endl;   
  24. while(n!=i)   
  25. {   
  26.   
  27. ++n;   
  28.   
  29. p1=new(student);   
  30. p1->rank=n;   
  31. cout<<"Construct the "<<n<<"th unit"<<endl<<endl;   
  32. p2->next=p1;   
  33. p2=p1;   
  34.   
  35. }   
  36. delete(p1);   
  37. p2->next=head;   
  38. return head;   
  39.   
  40.   
  41.   
  42.   
  43.   
  44. }   
  45.   
  46.   
  47. void fun(student *head,int j)   
  48. {   
  49.   
  50.   student *p;   
  51.   student *n;   
  52.   
  53.     n=head;   
  54.       if(n==n->next)   
  55.   {   final=n->next;   
  56.       return;   
  57.   }   
  58.   int round=j;   
  59.   while(round)   
  60.   {   
  61.     round--;   
  62.     p=n;   
  63.     n=p->next;   
  64.   
  65.   }   
  66.   
  67.   p->next=n->next;   
  68.   cout<<"Delete the  "<<n->rank<<"th unit"<<endl<<endl;   
  69.   
  70.     delete n;   
  71.   
  72.   
  73.   fun(p->next,j);   
  74.   
  75.   
  76.   
  77. }   
  78.   
  79.   
  80.   
  81.   
  82.   
  83.   
  84.   
  85.   
  86.   
  87.   
  88.   
  89.   
  90.   
  91.   
  92.   
  93.   
  94.   
  95.   
  96.   
  97.   
  98. int main()   
  99. {   
  100.    student *head1;   
  101.    int i,j;   
  102.    cout<<"Please input the number:";   
  103.    cin>>i;   
  104.   
  105.    head1=creat(i);   
  106.    cout<<"Please input the key:";   
  107.    cin>>j;   
  108.       fun(head1,j);   
  109.     cout<<"Remaining the "<<final->rank<<"th unit"<<endl;   
  110.   
  111.   return 0;   
  112.   
  113.   
  114. }   
  115.   
  116.   
  117.   

 

原创粉丝点击