thehitmanranjan

Josephus Algorithm

Sep 26th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. struct circle
  4. {
  5.     int id;
  6.     circle *next;
  7. };
  8. struct circle *ptr,*node,*start,*prev,*temp;
  9. int main()
  10. {
  11.     int n,k,elimination=0,counter=0;
  12.     cin>>n;
  13.     cin>>k;
  14.     ptr=new circle;                 //First Node
  15.     ptr->id=1;
  16.     start=ptr;
  17.     for(int i=2;i<=n;i++)           //Creating of Circualar queue
  18.     {
  19.         node=new circle;
  20.         node->id=i;
  21.         ptr->next=node;
  22.         ptr=node;
  23.     }
  24.     ptr->next=start;
  25.     ptr=start;
  26.     while(elimination!=n-1)
  27.     {
  28.         counter++;
  29.         if(counter==k)
  30.         {
  31.             prev->next=ptr->next;
  32.             temp=ptr->next;
  33.             delete ptr;
  34.             ptr=temp;
  35.             elimination++;
  36.             counter=0;
  37.         }
  38.         else
  39.         {
  40.             prev=ptr;
  41.             ptr=ptr->next;
  42.         }
  43.     }
  44.     cout<<ptr->id;
  45. }
Add Comment
Please, Sign In to add comment