不敢死队问题

1.知识点:循环链表
2.题意:已知排长是1号,从1号开始数,数到5的那名战士去执行任务,那么排长是第几个去执行任务的
3.注意事项:注意循环链表删除节点的前后节点的指针域的指向变化

代码:

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int Data;
    struct node *next;
}*head, *tail;
void Build(int n);//顺序建立循环链表
void Search_ans();//在循环链表中查找最优解
int main()
{
    int n;
    while(scanf("%d", &n) && n != 0)
    {
        if(n == 1)
            printf("%d\n", n);
        else
        {
            head = (struct node *)malloc(sizeof(struct node));
            head->Data = 1;
            head->next = NULL;
            tail = head;
            Build(n);//顺序建立循环链表
            Search_ans();//在循环链表中查找最优解
        }
    }
    return 0;
}
void Build(int n)//顺序建立循环链表
{
    struct node *p;
    for(int i = 2; i < n; i++)
    {
        p = (struct node *)malloc(sizeof(struct node));
        p->Data = i;
        p->next = tail->next;
        tail->next = p;
        tail = p;
    }
    p = (struct node *)malloc(sizeof(struct node));
    p->Data = n;
    tail->next = p;
    p->next = head;
}
void Search_ans()//在循环链表中查找最优解
{
    int cnt = 0;//判断当前结点是否符合执行任务的题意
    int flag = 1;//记录之前有几名士兵执行任务
    struct node *q, *p;
    q = tail->next;
    p = head;
    while(1)//通过while循环中的符合题意的语句中的break语句来结束while循环
    {
        cnt++;
        if(cnt % 5 == 0)
        {
            if(p->Data == 1)
            {
                printf("%d\n", flag);
                break;
            }
            else
            {
                q->next = p->next;
                free(p);
                p = q->next;
                flag++;
            }

        }
        else
        {
            q = p;
            p = p->next;
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值