【学习版】
【C语言】
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef struct Lnode {int date;struct Lnode* next;
}Lnode, * Linklist;
int In(Linklist& L) {L = new Lnode;L->next = NULL;return 0;
}
void Cl(Linklist& L, int n) {Lnode* r = L;for (int i = 1; i <= n; i++) {Lnode* p = new Lnode;p->date = i;p->next = NULL;r->next = p;r = p;}r->next = L->next;}
int main()
{std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);int n, m, count = 0;Linklist A;In(A);cin >> n;Cl(A, n);cin >> m;Lnode* p = A;while (n > 1) {if (count == m) {Lnode* q = p->next;p->next = q->next;delete q;count = 0;n--;}else {for (int i = 1; i < m; i++) {p = p->next;}count = m;}}cout << p->next->date;return 0;
}
【C++】
#include<iostream>struct LinkedNode {int val;LinkedNode* next;LinkedNode(int x) :val(x), next(nullptr) {};
};
void initList(LinkedNode* list,int n) {LinkedNode* cur = list;for (int i = 1; i <= n; i++) {LinkedNode* newNode = new LinkedNode(i);cur->next = newNode;cur = cur->next;}cur->next = list->next;
}
void deleteList(LinkedNode* list, int n,int k) {LinkedNode* cur = list;while (n > 1) {for (int i = 0; i < k-1; i++) {cur = cur->next;}LinkedNode* tmp = cur->next;cur->next = cur->next->next;delete tmp;n--;}std::cout << cur->val;
}
int main() {LinkedNode* list = new LinkedNode(0);int n, k;std::cin >> n >> k;initList(list, n);deleteList(list, n, k);return 0;
}
【STL】
#include<iostream>
#include<vector>int main() {int n, k;std::cin >> n >> k;std::vector<int> vec(n);for (int i = 0; i < n; i++) vec[i] = i + 1;int cur = 0;while (vec.size() > 1) {cur = (cur + k -1) % vec.size();vec.erase(vec.begin() + cur);}std::cout << vec[0];return 0;
}