题目( 单选题 )
下列C++代码用循环链表解决约瑟夫问题,即假设 n 个人围成一圈,从第一个人开始数,每次数到第 k 个 的人就出圈,输出最后留下的那个人的编号。横线上应填写( )。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
struct Node { int data; Node* next; }; Node* createCircularList(int n) { Node* head = new Node{ 1, nullptr }; Node* prev = head; for (int i = 2; i <= n; ++i) { Node* node = new Node{ i, nullptr }; prev->next = node; prev = node; } prev->next = head; return head; } int fingLastSurvival(int n, int k) { Node* head = createCircularList(n); Node* p = head; Node* prev = nullptr; while (p->next != p) { for (int count = 1; count < k; ++count) { prev = p; p = p->next; } _______________________ } cout << "最后留下的人编号是: " << p->data << endl; delete p; return 0; } |

关注我们