#include<stdio.h>#include<stdlib.h>struct node
{int data;struct node *next;};intmain(void){int n, m;int i, count =1;struct node *head,*tail,*p,*q,*newNode;
head =(struct node *)malloc(sizeof(struct node));
head->next =NULL;
tail = head;while(1){scanf("%d %d",&n,&m);if(n ==0|| m ==0){free(head);break;}else{for(i =0; i < n; i++){
newNode =(struct node *)malloc(sizeof(struct node));
newNode->data = i +1;
tail->next = newNode;
newNode->next = head->next;
tail = newNode;}
q = tail;//前结点
p = head->next;//后结点while(q != p){if(count == m){
q->next = p->next;free(p);
p = q->next;
count =1;}else{
q = p;
p = p->next;
count++;}}printf("%d\n", p->data);free(p);}}return0;}
使用数组或迭代
#include<iostream>#include<stdio.h>usingnamespace std;intyuesefu(int n,int m){if(n ==1){return0;//这里返回下标,从0开始,只有一个元素就是剩余的元素0}else{return(yuesefu(n-1,m)+ m)% n;//我们传入的n是总共多少个数}}intmain(void){int a,b;while(cin >> a >> b, a || b)
cout <<yuesefu(a,b)+1<<endl;//或者,直接循环迭代,求出来的result如上int result =0;for(int i =2;i <= a;i++){
result =(result+b)%i;}
cout<<result<<endl;return0;}