Find last 2 survivors in N persons standing in a circle after killing next to immediate neighbour | Java implementation of the approach ; Node for a Linked List ; Function to find the last 2 survivors ; Total is the count of alive people ; Initiating the list of n people ; Total != 2 is terminating condition because at last only two - person will remain alive ; Del represent next person to be deleted or killed ; Last two person to survive ( in any order ) ; Driver code
class GFG { static class Node { int val ; Node next ; Node ( int _val ) { val = _val ; next = null ; } } ; static void getLastTwoPerson ( int n ) { int total = n ; Node head = new Node ( 1 ) ; Node temp = head ; for ( int i = 2 ; i <= n ; i ++ ) { temp . next = new Node ( i ) ; temp = temp . next ; } temp . next = head ; temp = head ; Node del ; while ( total != 2 ) { del = temp . next . next ; temp . next . next = temp . next . next . next ; temp = temp . next ; del = null ; System . gc ( ) ; total -= 1 ; } System . out . print ( temp . val + " ▁ " + temp . next . val ) ; } public static void main ( String [ ] args ) { int n = 2 ; getLastTwoPerson ( n ) ; } }