提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、问题
二、代码
18普通版
代码如下:
#include<iostream>
#include<iomanip>
using namespace std;
struct node
{
int data;
node *next;
};
node *create_set(int n)
{
node *p1,*p2=NULL,*head;
int a;
head=NULL;
cout<<"正在创建一条循环列表...\n";
for(a=1;a<=n;a++)
{
p1=new node;
p1->data=a;
if(head==NULL)
head=p2=p1;
else
{
p2->next=p1;
p2=p1;
}
}
if(head!=NULL)
p2->next=head;
return(head);
}
void count_list(node*head,int m)
{
node*p1;
int i=1,b;
cout<<"依次退出圈子的人为:";
while((head->data)!=(head->next)->data)
{
if(i==(m-1))
{
i=0;
b=(head->next)->data;
cout<<b<<endl;
p1=head->next;
head->next=(head->next)->next;
delete p1;
}
else
{
i++;
head=head->next;
}
}
b=head->data;
cout<<"留在圈子里的人的序号:"<<b<<endl;
delete head;
}
int main()
{
node*head;
int n,m;
cout<<"请输入圈子的人数:"<<endl;
cin>>n;
cout<<"请输入m的值:"<<endl;
cin>>m;
head=create_set(n);
count_list(head,m);
return 0;
}
18提升版
代码如下:
#include<iostream>
#include<iomanip>
using namespace std;
struct node
{
int data;
node *next;
};
node *create_set(int n)
{
node *p1,*p2=NULL,*head;
int a;
head=NULL;
cout<<"正在创建一条循环列表...\n";
for(a=1;a<=n;a++)
{
p1=new node;
p1->data=a;
if(head==NULL)
head=p2=p1;
else
{
p2->next=p1;
p2=p1;
}
}
if(head!=NULL)
p2->next=head;
return(head);
}
void free(node*head)
{
node*p;
while(head->next)
{
p=head;
head=head->next;
delete p;
}
delete head;
}
void count_list(node*head,int m)
{
node*p1,*p2;
int i=1,b;
cout<<"依次退出圈子的人为:";
if(m==1)
{
p2=head;
while(head->next&&head->next!=p2)
{
b=head->data;
p1=head;
head=head->next;
cout<<b<<endl;
delete p1;
}
}
else
{
while(head!=head->next)
{
if(i==m-1)
{
i=0;
b=(head->next)->data;
cout<<b<<endl;
p1=head->next;
head->next=(head->next)->next;
delete p1;
}
else
{
i++;
head=head->next;
}
}
}
b=head->data;
cout<<"留在圈子里的人的序号:"<<b<<endl;
delete head;
}
int main()
{
node*head;
int n,m;
cout<<"请输入圈子的人数:"<<endl;
cin>>n;
cout<<"请输入m的值:"<<endl;
cin>>m;
head=create_set(n);
count_list(head,m);
return 0;
}
总结
创作不易,如果这篇文章帮到你的话,可以点赞支持一下哦。