假设 n 个人围成一圈,从第一个人开始数,每次数到第 k 个的人就出圈,输出最后留下的那个人的编号。
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;
}