Vijos数据结构基础C++实验整理(七)——卡片游戏(队列应用)

该博客介绍了一个使用队列实现的C++程序,模拟了桌上扑克牌的操作过程。当扑克牌数量大于等于2时,将第一张牌移除并将第二张牌移到末尾。程序通过一个扩展的数组队列类实现,包括了初始化、操作和输出等功能,并给出了样例输入和输出。
摘要由CSDN通过智能技术生成

实验内容:
假设桌上有一叠扑克牌,依次编号为1-n(从上至下)。当至少还有两张的时候,可以进行操作:把第一张牌扔掉,然后把新的第一张(原先扔掉的牌下方的那张牌,即第二张牌)放到整叠牌的最后。输入n,输出最后剩下的牌。

样例:
输入
100
输出
72

代码实现:

#include<iostream>
using namespace std;

class queue
{
public:
    virtual ~queue() {}
    virtual bool empty() const = 0;
    virtual int size() const = 0;
    virtual int& front() = 0;
    virtual int& back() = 0;
    virtual void pop() = 0;
    virtual void push(const int& theElement) = 0;
    virtual void output() = 0;
};


class extendedarrayQueue : public queue
{
public:
    extendedarrayQueue(int initialCapacity = 10);
    ~extendedarrayQueue() { delete[] queue; }
    bool empty() const { return theFront == theBack; }
    int size() const {
        return (theBack - theFront + arrayLength) % arrayLength;
    }
    int& front() {
        return queue[(theFront + 1) % arrayLength];
    }
    int& back() {
        return queue[theBack];
    }
    void pop() {
        theFront = (theFront + 1) % arrayLength;
        ~queue[theFront];
    }
    void push(const int& theElement);
    void initial(int n);
    void output();
    void play();
private:
    int theFront;
    int theBack;
    int arrayLength;
    int* queue;
};


extendedarrayQueue::extendedarrayQueue(int initialCapacity)
{
    arrayLength = initialCapacity;
    queue = new int[arrayLength];
    theFront = 0;
    theBack = 0;
}

void extendedarrayQueue::initial(int n) {
    for (int i = 1;  i <= n; i++) {
        push(i);
    }
}

void extendedarrayQueue::play() {
    while (size() >= 2) {
        pop();
        int trans = front();
        pop();
        push(trans);
    }
}

void extendedarrayQueue::push(const int& theElement)
{
    if ((theBack + 1) % arrayLength == theFront)
    {
        int* newQueue = new int[2 * arrayLength];

        int start = (theFront + 1) % arrayLength;
        if (start < 2)

            copy(queue + start, queue + start + arrayLength - 1, newQueue);
        else
        {
            copy(queue + start, queue + arrayLength, newQueue);
            copy(queue, queue + theBack + 1, newQueue + arrayLength - start);
        }

        theFront = 2 * arrayLength - 1;
        theBack = arrayLength - 2;
        arrayLength *= 2;
        queue = newQueue;
    }

    theBack = (theBack + 1) % arrayLength;
    queue[theBack] = theElement;
}

void extendedarrayQueue::output() {
    for (int i = (theFront + 1) % arrayLength; i < (theFront + 1) % arrayLength + size(); i++) {
        cout << queue[i];
    }
    cout << endl;
}


int main() {
    int n;
    cin >> n;
    extendedarrayQueue A;
    A.initial(n);
    A.play();
    A.output();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值