数据结构算法——1014. 循环打印

本文介绍了一个经典的Josephus问题,并使用环形链表进行求解。通过构建环形链表来模拟问题场景,实现了指定间隔的元素删除过程,最终得到问题的解答。

题目

在这里插入图片描述

思路

Josephus排列问题,用一个环形链表就可以解决了,环形链表思路详细看数据结构笔记部分

代码

#include<iostream>
using namespace std;    

struct list
{
    int data;
    list* prev = NULL;
    list* next = NULL;
};

struct L
{
    
    list* init(int n)
    {
        list* head = new list;
        list* tail = head;
        head->data = 1;

        for(int i = 2; i <= n; i++)
        {
            list* temp = new list;
            tail->next = temp;
            temp->data = i;
            temp->prev = tail;
            tail = temp;
        }
        tail->next = head;
        head->prev = tail;
        return head;
    }

    list* del(list* dot)
    {
        if(dot->next == dot)
        {
            cout << dot->data << endl;
            delete dot;
            return NULL;
        }
        else
        {
            list*temp = dot->next;
            dot->prev->next = dot->next;
            dot->next->prev = dot->prev;
            cout << dot->data << " ";
            delete dot;
            return temp;
        }
    }

    list* print(list* head, int first, int step)
    {
        for(int i = 1; i < first + step - 1; i++)
        {
            head = head->next;
        }
        //cout << head->data << endl;
        while(head)
        {
            head = del(head);
            for(int i = 0; i < step - 1; i++)
                if(head)
                    head = head->next;
        }
        return head;
    }
};

int main()
{
    int n,start,step;
    cin >> n >> start >> step; 
    L a;
    list* head = a.init(n);
    a.print(head,start,step);
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值