C语言双向链表题目:猴子选大王/夏令营骑手

猴子选大王 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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值