题目

思路
Josephus排列问题,用一个环形链表就可以解决了,环形链表思路详细看数据结构笔记部分
代码
#include<iostream>
using namespace std;
struct list
{
int data;
list* prev = NULL;
list* next = NULL;
};
struct L
{
list* init(int n)
{
list* head = new list;
list* tail = head;
head->data = 1;
for(int i = 2; i <= n; i++)
{
list* temp = new list;
tail->next = temp;
temp->data = i;
temp->prev = tail;
tail = temp;
}
tail->next = head;
head->prev = tail;
return head;
}
list* del(list* dot)
{
if(dot->next == dot)
{
cout << dot->data << endl;
delete dot;
return NULL;
}
else
{
list*temp = dot->next;
dot->prev->next = dot->next;
dot->next->prev = dot->prev;
cout << dot->data << " ";
delete dot;
return temp;
}
}
list* print(list* head, int first, int step)
{
for(int i = 1; i < first + step - 1; i++)
{
head = head->next;
}
//cout << head->data << endl;
while(head)
{
head = del(head);
for(int i = 0; i < step - 1; i++)
if(head)
head = head->next;
}
return head;
}
};
int main()
{
int n,start,step;
cin >> n >> start >> step;
L a;
list* head = a.init(n);
a.print(head,start,step);
return 0;
}
本文介绍了一个经典的Josephus问题,并使用环形链表进行求解。通过构建环形链表来模拟问题场景,实现了指定间隔的元素删除过程,最终得到问题的解答。
1168

被折叠的 条评论
为什么被折叠?



