Coding Solution of A Knife Game

Question:-

Suppose n people are standing in a circle. If the 1st person has a knife and he kills the 2nd person and passes the knife to the 3rd person. After that, the 3rd person does the same, and so on. Then, find the winner person who will be alive at the last?

Logic:-

Program:-
//this program is developed by thezenithcoder.blogspot.com/MONISH KR. BAIRAGI
#include<stdio.h>
#include<malloc.h>

struct node{int info; struct node *next; } *ptr,*temp,*start=NULL; 
int c=0;

void create(int n) {
    int i;
    if(n >= 1) {
        start = (struct node*)malloc(sizeof(struct node));
        c++;
        start->info = c;
        start->next = NULL;
        ptr = start;
        for(i=2; i<=n; i++) {
            temp = (struct node *)malloc(sizeof(struct node));
            c++;
            temp->info = c;
            temp->next = NULL;
            ptr->next = temp;
            ptr = temp;
        }
        ptr->next = start;
    } 
}

void main() {
    int n;
    printf("Enter total no. of persons:"); 
    scanf("%d",&n); 
    create(n); 
    ptr=start;
    while(ptr!=ptr->next) { 
        temp=ptr->next;
        ptr->next=temp->next;
        free(temp);
        ptr=ptr->next; 
    }
    if(ptr==ptr->next) {
        printf("%d\n",ptr->info);
    }
}
Output:-



Developer:-
Name: Monish Kumar Bairagi
Department: Computer Science and Engineering
Batch: 2018 - 2022
College: Hooghly Engineering and Technology College

Post a Comment

0 Comments