C++ 队列的实现

队列是一种先进先出的数据结构,其实现如下

数组实现

#include<iostream>
#include<cstring>
using namespace std;
const int MAX = 5;
template <class T>
class queue_array{
    int head, rear, m_size;
    T data[100];
    public:
    queue_array(){
        head = rear = -1;
        m_size = MAX;
        memset(data, 0, sizeof(data));
    }
    void enqueue(T x){
        if(rear == m_size - 1) cout << "full\n";
        else data[++rear] = x;
    }
    T dequeue(){
        if(rear == head) {cout << "empty\n"; exit(0);}
        else return data[++head];
    }
    bool is_empty(){
        return head == rear;
    }
    int size(){
        return rear - head;
    }
};
int main(){
queue_array<int> q;
return 0;
}

链表实现

#include<iostream>
using namespace std;
template <class T>
class node{
    public:
    T data;
    node<T> *next;
    node(){
        data = NULL;
        next = NULL;
    }
    node(T x, node<T> *ptr){
        data = x;
        next = ptr;
    }
};
template <class T>
class queue_linknode{
    node<T> *head, *rear;
    int cnt = 0;
    public:
    queue_linknode(){
        head = new node<T>();
        rear = new node<T>();
    }
    void push(T x){
        node<T> *t = new node<T>(x, NULL);
        if(cnt == 0){head = rear = t;}
        else{rear->next = t; rear = t;}
        cnt++;
    }
    T pop(){
        if(cnt == 0){cout << "empty\n"; exit(0);}
        T t = head->data;
        head = head->next;
        cnt--;
        return t;
    }
    bool is_empty(){
        return cnt == 0;
    }
    int size(){
        return cnt;
    }
};

int main(){
     queue_linknode<int> q;
     return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值