Lucky alive person in a circle | Code Solution to sword puzzle | 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
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function newNode ( data ) { var node = new Node ( ) ; node . data = data ; node . next = null ; return node ; } function alivesol ( Num ) { if ( Num == 1 ) return 1 ; var last = newNode ( 1 ) ; last . next = last ; for ( var i = 2 ; i <= Num ; i ++ ) { var tem = newNode ( i ) ; tem . next = last . next ; last . next = tem ; last = tem ; } var curr = last . next ; var tem1 = new Node ( ) ; while ( curr . next != curr ) { tem1 = curr ; curr = curr . next ; tem1 . next = curr . next ; tem1 = tem1 . next ; curr = tem1 ; } var res = tem1 . data ; return res ; } var N = 100 ; document . write ( alivesol ( N ) + " " ) ;