04-顺序表和堆栈练习-
题目描述
N个人坐成一个圆环(编号为1 - N),从第S个人开始报数,数到K的人出列,后面的人重新从1开始报数。问最后剩下的人的编号。
例如:N = 3,K = 2,S = 1。2号先出列,然后是1号,最后剩下的是3号。
要求使用循环链表实现。
输入
测试数据有多组
每组包括3个数N、K、S,表示有N个人,从第S个人开始,数到K出列。(2 <= N <= 10^6,1 <= K <= 10, 1 <= S <= N)
输出
出列的人的编号
输入样例1
13 3 1
3 2 1
3 6 9 12 2 7 11 4 10 5 1 8 13
2 1 3
#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
void create(node *H,int &n)//循环链表创建
{
H->next=NULL;
struct node *p=H,*s;
int e=0,i;
for(i=0;i<n;i++)
{
++e;
s=new node;s->next=NULL;s->data=e;
p->next=s;
p=s;
}
p->next=H->next;
}
void find(node *H,int n,int k,int s)
{
int i;
struct node *p=H;
struct node *q=NULL;
while(p->data!=s)//找到第一个开始的位置
p=p->next;
while(p->next!=p) //核心函数
{
for(i=0;i<k-1;i++)//经过k-1个人出局
{
q=p;
p=p->next;
}
cout<<p->data<<" ";//出局的人,位置即data
q->next=p->next;
p=q->next;
}
cout<<p->data<<" "; //最后出局的人
cout<<"\n";
}
int main()
{
int k,n,s,i;
while(scanf("%d%d%d",&n,&k,&s)!=EOF)//无限输入
//while(cin>>n>>k>>s) //c++法
{
node *L=new node;
create(L,n);
find(L,n,k,s);
delete L;
}
return 0;
}