第一种:构建循环链表,然后不断遍历链表直到剩下最后一个元素。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef struct list
{
int data;
struct list *next;
}list,*link;
int main(){
link p = NULL,q = NULL,head = NULL;
int i,n,m;
scanf("%d %d",&n,&m);
head = (link)malloc(sizeof(list));
q = head;
for(i = 1;i <= n;i++) //构造循环链表
{
p = (link)malloc(sizeof(list));
p -> data = i;
q -> next = p;
q = p;
}
p -> next = head -> next;
p = head -> next;
free(head);
while(p -> next != p) i < m - 1 是因为第一次循环 p 位于 第一个节点 与第m个节点中间隔有m-2个节点 所以执行m-2次循环
{
for(i = 1;i < m - 1;i++)
{
p = p -> next;
}
p -> next = p -> next -> next;
p = p -> next;
}
printf("%d\n",p -> data);
return 0;
}
第二种:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<cstdlib>
#include<algorithm>
using namespace std;
int main(){
int n,m;
int p,q,t,i;
int a[300];
scanf("%d %d",&n,&m);
memset(a,0,sizeof(a));
q = n;
p = 0;
for(i = 0;i < n;i++) a[i] = i + 1;
for(i = 0;;i++)
{
if(i == n) i = 0;
if(a[i] != 0) p++;
else continue;
if(p % m == 0)
{
a[i] = 0;
q--;
}
if(q == 1) break;
}
for(i = 0;i < n;i++)
{
if(a[i]) printf("%d\n",a[i]);
}
return 0;
}