PROGRAM TO IMPLEMENT THE JOSEPHUS PROBLEM.
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
using namespace std;
class C_List;
class Node
{
friend class C_List;
friend class Josephus;
private:
char Name[100];
Node *Link;
};
class Josephus;
class C_List
{
friend class Josephus;
private:
Node *Last;
public:
C_List()
{
Last = NULL;
}
void Insert(char *Naam)
{
Node *Temp = new Node;
strcpy(Temp->Name , Naam);
if(IsEmpty())
Last = Temp;
else
Temp->Link = Last->Link;
Last->Link = Temp;
}
void Delet_After(Node *Test)
{
if( Test == NULL || Test == Test->Link)
{
cout << "DELETION IS NOT POSSIBLE...!!!" << endl;
exit(1);
}
Node *Temp = Test->Link;
cout << "Node to Be Deleted is: " << Temp->Name << endl;
Test->Link = Temp->Link;
delete(Temp);
}
inline bool IsEmpty()
{
return Last == NULL;
}
};
class Josephus
{
private:
int No;
char Name1[100];
public:
Josephus()
{
No = 0;
strcpy(Name1, "NULL");
}
void Joseph_Problem()
{
C_List Obj;
while(strcmp(Name1, "end") != 0)
{
cout << "Enter the Name: ";
cin >> Name1;
Obj.Insert(Name1);
}
cout << "\nEnter Any Number: ";
cin >> No;
cout << endl;
while(Obj.Last != Obj.Last->Link)
{
for(int I =0 ; I < No -1; I++)
Obj.Last = Obj.Last->Link;
Obj.Delet_After(Obj.Last);
}
cout << "\nNode That Will Escape is: " << Obj.Last->Name << endl;
}
};
int main()
{
Josephus Obj;
Obj.Joseph_Problem();
getch();
return 0;
}
0 comments:
Post a Comment