暑假自学
Posted buxiang-christina
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了暑假自学相关的知识,希望对你有一定的参考价值。
今天是小学期的最后一天题目是约瑟夫问题的求解,代码如下:
#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;
}
以上是关于暑假自学的主要内容,如果未能解决你的问题,请参考以下文章