Lucky alive person in a circle | Code Solution to sword puzzle | C ++ code to find the luckiest person ; Node structure ; Function to find the luckiest person ; Create a single node circular linked list . ; Starting from first soldier . ; condition for evaluating the existence of single soldier who is not killed . ; deleting soldier from the circular list who is killed in the fight . ; Returning the Luckiest soldier who remains alive . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> next = NULL ; return node ; } int alivesol ( int Num ) { if ( Num == 1 ) return 1 ; Node * last = newNode ( 1 ) ; last -> next = last ; for ( int i = 2 ; i <= Num ; i ++ ) { Node * temp = newNode ( i ) ; temp -> next = last -> next ; last -> next = temp ; last = temp ; } Node * curr = last -> next ; Node * temp ; while ( curr -> next != curr ) { temp = curr ; curr = curr -> next ; temp -> next = curr -> next ; delete curr ; temp = temp -> next ; curr = temp ; } int res = temp -> data ; delete temp ; return res ; } int main ( ) { int N = 100 ; cout << alivesol ( N ) << endl ; return 0 ; }