Find last 2 survivors in N persons standing in a circle after killing next to immediate neighbour | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int val ; struct Node * next ; Node ( int _val ) { val = _val ; next = NULL ; } } ; void getLastTwoPerson ( int n ) { int total = n ; struct Node * head = new Node ( 1 ) ; struct Node * temp = head ; for ( int i = 2 ; i <= n ; i ++ ) { temp -> next = new Node ( i ) ; temp = temp -> next ; } temp -> next = head ; temp = head ; struct Node * del ; while ( total != 2 ) { del = temp -> next -> next ; temp -> next -> next = temp -> next -> next -> next ; temp = temp -> next ; free ( del ) ; total -= 1 ; } cout << temp -> val << " ▁ " << temp -> next -> val ; } int main ( ) { int n = 2 ; getLastTwoPerson ( n ) ; return 0 ; }