Last active
July 28, 2019 07:01
-
-
Save Kinjalrk2k/cea492d96544e57582e29bcbfb3e326e to your computer and use it in GitHub Desktop.
Demonstrating Josephus problem using Singly Circular Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
typedef struct Node{ | |
int data; | |
struct Node* next; | |
}node; // nickname :) | |
void display(node *head) | |
{ | |
node* ptr = head; | |
do{ | |
printf("%d -> ", ptr->data); | |
ptr = ptr->next; | |
}while(ptr != head); | |
printf("\b\b\b\b \b\b\b\n"); | |
} | |
node* create_CLL(int size) | |
{ | |
node *head; | |
head = (node *) malloc(sizeof(node)); | |
head->data = 1; | |
head->next = NULL; | |
node *ptr = head; | |
for(int i=0; i<size-1; i++){ | |
node *newNode = (node *) malloc(sizeof(node)); | |
newNode->data = i+2; | |
newNode->next = NULL; | |
ptr->next = newNode; | |
ptr = ptr->next; | |
} | |
ptr->next = head; | |
return head; | |
} | |
void josephus(node *head, int skip) | |
{ | |
node *ptr = head; | |
display(head); | |
while(ptr->next != ptr){ | |
for(int i=0; i<skip; i++) | |
ptr = ptr->next; | |
node *toDel = ptr->next; | |
ptr->next = ptr->next->next; | |
free(toDel); | |
ptr = ptr->next; | |
display(ptr); | |
} | |
} | |
int main() | |
{ | |
int size = 10, skip = 0; | |
node *head = create_CLL(10); | |
display(head); | |
josephus(head, skip); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment