您的位置:首页 > 其它

josephus问题->不带头节点的循环链表

2017-03-02 11:33 344 查看
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}NODE;
NODE* create_circlelist(int n) //建立不带头节点的循环单链表
{
NODE* head;
NODE* p;
NODE* q;
p = new NODE;
p->data = 1;
head = p;
for(int i=2;i<=n;i++)
{
q = new NODE;
q->data = i;
p->next = q;
p = q; //p永远指向最后一个节点
}
p->next = head;
return head;
}
void josephus(NODE* head,int pos,int step)
{
int i=1;
NODE* front = NULL;
NODE* temp = head;
while(temp->data != pos)
{
temp = temp->next;
}
while(temp!=temp->next)
{
for(int i=0;i<step-1; i++)
{
front = temp;
temp = temp->next;
}
cout<<"the"<<i++<<"kill number is:";
cout<<temp->data<<" "<<endl;
front->next = temp->next;
delete temp;
temp = front->next;
}
cout<<"the "<<i++<<" kill Number is:";
cout<< temp->data<<endl;
delete temp;
}
#if 1
int main(int n, char*m[])
{
cout<<"input the size:";
int size;
cin>>size;
cout<<"input the start pos:";
int pos;
cin>>pos;
cout<<"input the circle number:";
int step;
cin>>step;
NODE* head = create_circlelist(size);
josephus(head,pos,step);
return 0;
}
#else
int main(int n, char*m[])
{
int size=atoi(m[1]);
int pos =atoi(m[2]);
int step =atoi(m[3]);
NODE* head = create_circlelist(size);
josephus(head,pos,step);
return 0;
}
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: