猴子选大王 2166
成圈的链表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
//
struct _line
{
int num;
struct _line *last;
struct _line *next;
};
int main()
{
int n,k;
scanf("%d%d",&n,&k);
struct _line *head,*p;
head=p=(struct _line *)malloc(sizeof(struct _line));
p->num=1;
int i;
for(i=2;i<=n;i++)
{
p->next=(struct _line *)malloc(sizeof(struct _line));
p->next->last=p;
p=p->next;
p->num=i;
}
p->next=head;
head->last=p;
p=head;
int s=n;
while(s>1)
{
int t=(k-1)%s;
for(i=1;i<=t;i++)
{
p=p->next;
}
p->next->last=p->last;
p->last->next=p->next;
printf("%d ",p->num);
p=p->next;
s--;
}
printf("%d\n",p->num);
return 0;
}
夏令营骑手 2170
和上面一题类型,不过不是成圈的,到了尽头就要原路返回,在判断下一个是否是尽头的时候要判断一次fx,在删除后将p移向下一个的时候还要判断一下fx (也可能是我太笨了没想到更好的办法0.0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
//
struct _line
{
int num;
struct _line *last;
struct _line *next;
};
int main()
{
int n,k;
scanf("%d%d",&n,&k);
struct _line *head,*p;
head=p=(struct _line *)malloc(sizeof(struct _line));
head->last=NULL;
p->num=1;
int i;
for(i=2;i<=n;i++)
{
p->next=(struct _line *)malloc(sizeof(struct _line));
p->next->last=p;
p=p->next;
p->num=i;
}
p->next=NULL;
p=head;
int s=n;
int fx=1;
while(s>1)
{
int t=(k-1)%(2*s-2);
for(i=1;i<=t;i++)
{
if(fx)
{
if(p->next!=NULL)
p=p->next;
else
{
p=p->last;
fx=0;
}
}
else
{
if(p->last!=NULL)
p=p->last;
else
{
p=p->next;
fx=1;
}
}
}
if(p->last!=NULL)
p->last->next=p->next;
if(p->next!=NULL)
p->next->last=p->last;
if(fx)
{
if(p->next!=NULL)
p=p->next;
else
{
p=p->last;
fx=0;
}
}
else
{
if(p->last!=NULL)
p=p->last;
else
{
p=p->next;
fx=1;
}
}
s--;
}
printf("%d\n",p->num);
return 0;
}