用户输入M,N值,从1至N开始顺序循环数数,每数到M输出该数值,直至全部输出。
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
void createList(node *&head, node *&tail, int n){
if(n < 1){
head = NULL;
return;
}
head = new node();
head->data = 1;
head->next = NULL;
node *p = head;
for(int i = 2; i <= n; ++i){
p->next = new node();
p = p->next;
p->data = i;
p->next = NULL;
}
tail = p;
p->next = head;
}
void Print(node *head){
node *p = head;
while(p && p->next != head){
cout << p->data << " ";
p = p->next;
}
if(p)
cout << p->data << endl;
}
void countPrint(node *&head, node *&tail, int m){
node *cur = head;
node *pre = tail;
int cnt = m - 1;
while(cur && cur != cur->next){
if(cnt){
cnt--;
pre = cur;
cur = cur->next;
}
else{
pre->next = cur->next;
cout << cur->data << " ";
delete cur;
cur = pre->next;
cnt = m - 1;
}
}
if(cur){
cout << cur->data << endl;
delete cur;
head = tail = NULL;
}
}
int main(){
node *head, *tail;
int n, m;
cin >> n >> m;
createList(head, tail, n);
Print(head);
countPrint(head, tail, m);
return 0;
}