c++ - Last man standing , used circular linked list -


question : company hiring candidates, makes them sit in circle. select every second candidate , leaves circle (thus circle keeps getting smaller), till 1 left. so, if there 5 people, it'll :-

1 2 3 4 5 1 3 4 5    (2 selected) 1 3 5      (4 selected) 3 5        (1 selected) 3          (3 left, does'nt job!) 

jhon oversmart guy doesn't want part of spiteful company.

where stand if knows there 560 people in total. ans : tried make program enter n(number of candidates) , it'll print value of 1 seat go unselected.

i used circular linked list , deletion.

please bear me , new coding .

my program works inputs 2, 4, 8, 16, 32, 64 , on ans in these 1. other input , it's not working.

#include <iostream>  using namespace std;  struct node {     node* ptr;     int data; }start;   int main() {     node *start=null;     int n;     cout<<"enter number of students : ";     cin>>n;     node *temp=new node;    temp->data=1;    temp->ptr=null;    start=temp;    for(int x=2;x<=n;x++)    {        node* temp1=new node;        temp1->data=x;        temp->ptr=temp1;        temp1->ptr=start;        temp=temp1;     }    node* temp2=start;       {        cout<<temp2->data<<" ";        temp2=temp2->ptr;    }while(temp2!=start);    cout<<endl;      //delete bigins here     temp2=start;    node* temp3=temp2->ptr;        {         temp2->ptr=temp3->ptr;         temp3->ptr=null;         delete temp3;         temp2=temp2->ptr;         temp3=temp2->ptr;      }while(temp2->ptr!=start);      temp2=start;       {        cout<<temp2->data<<" ";        temp2=temp2->ptr;    }while(temp2!=temp3);    cout<<endl; } 

my program works inputs 2, 4, 8, 16, 32, 64 , on ans in these 1.

this observation. answer small step here.

you have n candidates, , select 1 each time. if n x + 2^k (with biggest possible k), after x steps have 2^k candidates left , next candidate in line answer. answer 2x+1.

1 2 3 4 5 6 7   ^   ^   ^ |    removed  |        answer 

note: exercise can found in concrete mathematics: foundation computer science. highly recommend it.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -