标签:cin create 约瑟夫问题 head ++ stream main clu 今天
今天是小学期的最后一天题目是约瑟夫问题的求解,代码如下:
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node* next;
};
node* create()
{
int n;
node* head, * p1, * p2;
cout << "请输入人数:" << endl;
cin >> n;
if ( n < 1)
{
exit(0);
}
else
{
head = new node;
if(head==NULL)exit(0);
head->data=1;
head->next = NULL;
p1 = head;
for (int i=2;i <= n;i++)
{
p2 = new node;
p1->next = p2;
p1 = p1->next;
p1->data=i;
}
p1->next = head;
}
return head;
}
void findAndKillK(node* head, int stratId, int m)
{
node* p1;
p1 = head;
node* p2 = head;
while (p2->data != stratId)
{
p1 = p2;
p2 = p2->next;
}
while (p2->next != p2)
{
for (int i = 1; i < m; i++)
{
p1 = p2;
p2 = p2->next;
}
p1->next = p2->next;
cout << "出列的人的id是:";
cout << p2->data << endl;
free(p2);
p2 = p1->next;
}
cout << "出列的人的id是:";
cout << p2->data << endl;
free(p2);
}
int main()
{
node* head = create();
cout << "请输入stratId:" << endl;
int stratId;
cin >> stratId;
cout << "数到m的人出列:" << endl;
int m;
cin >> m;
findAndKillK(head, stratId, m);
return 0;
}
标签:cin create 约瑟夫问题 head ++ stream main clu 今天
原文地址:https://www.cnblogs.com/buxiang-Christina/p/13276378.html