#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int m, n;
struct Node{
int data;
Node *next;
} *head, *p, *tail, *temp;
void sc(Node *head,int m,int n){
Node *r,*p;
r=head;
p=r->next;
int t=0,k=0;
while(t!=m-1){
k++;
if(k==n){
r->next=p->next;
//cout<<p->data<<endl;
t++;
k=0;
}
else{
r=p;
}
p=p->next;
}
cout<<p->data<<endl;
}
int main(){
while(1){
cin>>m>>n;
if(n==0||m==0)return 0;
head = new Node;
head -> next = NULL;
tail = head;
for(int i = 1; i <= m; i++){
p = new Node;
p -> data = i;
p -> next = NULL;
tail -> next = p;
tail = p;
}
p = head -> next;
tail -> next = head -> next;
sc(head,m,n);
}
return 0;
}
上面的是对的,下面的是错的
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int m, n;
struct Node{
int data;
Node *next;
} *head, *p, *tail, *temp;
void sc(){
for(int i = 1; i < m; i++){
for(int j = 1; j < n - 1; j++){
p = p -> next;
}
temp = p -> next;
p -> next = temp -> next;
p = p -> next;
free(temp);
}
cout<<p->data<<endl;
return ;
}
int main(){
while(1){
cin>>m>>n;
if(n==0||m==0)return 0;
head = new Node;
head -> next = NULL;
tail = head;
for(int i = 1; i <= m; i++){
p = new Node;
p -> data = i;
p -> next = NULL;
tail -> next = p;
tail = p;
}
p = head -> next;
tail -> next = head -> next;
sc();
}
return 0;
}