其本质是约瑟夫环问题,这里用最基础的方法解。
#include <iostream>
using namespace std;
typedef struct node {
int num;
struct node* next;
}node;
node* insert(node* L, int n) {
node* q = L;
for (int i = 2; i < n + 1; i++) {
node* p = new node;
p->num = i;
q->next = p;
q = p;
q->next = L;
}
return L;
}
int main()
{
int n;
cin >> n;
node* p;
node* L;
p = new node;
L = p;
L->num = 1;
L->next = L;
L = insert(L, n);
int count = 1;
p = L;
while (p->next != p) {
if (count == 2) {
node* q;
q = p->next;
p->next = q->next;
free(q);
count = 0;
}
p = p->next;
count++;
}
cout << p->num;
}