您的位置:首页 > 其它

约瑟夫问题的简单实现过程

2012-12-06 14:59 239 查看
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

typedef struct circleList
{
int data;
struct circleList *next;
}node;

node *createList(int n)
{
node *head;
node *p;
int i;
head = (node *)malloc(sizeof(node));
p = head;
for(i = 0; i < n - 1; i++)
{
p->data = i + 1;
p->next = (node *)malloc(sizeof(node));
p = p->next;
}
p->data = n;
p->next = head;
return head;
}

node *deleteElement(node *head, int n)
{
int i;
node *p = head;
node *q = NULL;
if(p->next == p)
{

cout<<p->data<<endl;
return NULL;
}
else
{
q = p;
p = p->next;
}
for(i = 0; i < n - 1; i++)
{
p = p->next;
q = q->next;
}

cout<<p->data<<endl;
q->next = p->next;
return q->next;
}

void Jusephus(int n, int k, int m)
{
node *head = createList(n);
int i;
for(i = 0; i < k; i++)
{
head = head->next;
}
cout<<"Jusephus
Problem("<<n<<",
"<<k<<",
"<<m<<"):"<<endl;
while(head != NULL)
{
head = deleteElement(head, m);
}
}

void display(node *head)
{
if(head == NULL)
{
cout<<"Empty
List!"<<endl;
return ;
}
else
{
node *p = head;
cout<<"Elements of
List:"<<endl;
while(head->next != p)
{

cout<<head->data<<endl;
head = head->next;
}

cout<<head->data<<endl;
}
}

int main()
{
int n, k, m;
cout<<"input args of Jusephus
Problem:"<<endl;
cout<<"n = ";
cin>>n;
cout<<"k = ";
cin>>k;
cout<<"m = ";
cin>>m;
Jusephus(n, k, m);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: