C/C++ 语言练习之手撕队列

头文件实现

#ifndef ARRAY_QUEUE_HXX
#define ARRAY_QUEUE_HXX

#include <iostream>
using namespace std;

template<class T> class ArrayQueue{
    public:
        ArrayQueue();
        ~ArrayQueue();

        void add(T t);
        T front();
        T pop();
        int size();
        int is_empty();

    private:
        T *arr;
        int count;
};

// 创建“队列”,默认大小是12
template<class T>
ArrayQueue<T>::ArrayQueue() 
{
    arr = new T[12];
    if (!arr) 
    {
        cout<<"arr malloc error!"<<endl;
    }
}

// 销毁“队列”
template<class T>
ArrayQueue<T>::~ArrayQueue() 
{
    if (arr) 
    {
        delete[] arr;
        arr = NULL;
    }
}

// 将val添加到队列的末尾
template<class T>
void ArrayQueue<T>::add(T t) 
{
    arr[count++] = t;
}


// 返回“队列开头元素”
template<class T>
T ArrayQueue<T>::front() 
{
    return arr[0];
}

// 返回并删除“队首元素”
template<class T>
T ArrayQueue<T>::pop() 
{
    int i = 0;;
    T ret = arr[0];

    count--;
    while (i++<count)
        arr[i-1] = arr[i];

    return ret;
}

// 返回“队列”的大小
template<class T>
int ArrayQueue<T>::size() 
{
    return count;
}

// 返回“队列”是否为空

{
    return count==0;
}


#endif

测试

#include<iostream>
#include"ArrayQueue.h"
using namespace std;

int main(){
    int tmp = 0;
    ArrayQueue<int>* astack = new ArrayQueue<int>();
    // 将10, 20, 30 依次推入队列中
    astack->add(10);
    astack->add(20);
    astack->add(30);

    // 将“队列开头元素”赋值给tmp,并删除“该元素”
    tmp = astack->pop();
    cout<<"tmp="<<tmp<<endl;

    // 只将“队列开头的元素”赋值给tmp,不删除该元素.
    tmp = astack->front();
    cout<<"tmp="<<tmp<<endl;

    astack->add(40);

    cout<<"is_empty()="<<astack->is_empty()<<endl;
    cout<<"size()="<<astack->size()<<endl;
    while (!astack->is_empty())
    {
        tmp = astack->pop();
        cout<<tmp<<endl;
    }

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值