queue链表实现C++

#include <iostream>
using namespace std;

typedef struct _node{
    int data;
    struct _node* next;
    _node(int e ,struct _node* p = nullptr){
        data = e;
        next = p;   
    }
}node;

class queue{
public:
    queue():m_start(new node(-1,nullptr)),m_tail(m_start),m_length(0){}
    ~queue(){
        while(m_start->next != nullptr){
            node* pdel = m_start;
            m_start = m_start->next;
            delete pdel;
        }
        m_start = m_tail = nullptr;
    }
    void push(int e);
    void pop();
    int  front();
    int  back();
    bool isEmpty();
    int  size();    
private:
    node* m_start;
    node* m_tail;
    int   m_length;
};

void queue::push(int e){
    node* pnew = new node(e,nullptr);
    m_tail->next = pnew;
    m_tail = pnew;
    ++m_length;
}

void queue::pop(){
    if(m_start->next == nullptr){
        cout << "queue is empty.\n";
    }else{
        node* pdel = m_start->next;
        m_start->next = pdel->next;
        delete pdel;
        --m_length;
        if (m_length == 0){
            m_tail = m_start;
        }
    }
}

int  queue::front(){
    if(m_tail == m_start){
        cout << "queue is empty.\n";
        exit(1);
    }else{
        return m_start->next->data;
    }
}

int  queue::back(){
    if(m_tail == m_start){
        cout << "queue is empty.\n";
        exit(1);
    }else{
        return m_tail->data;
    }
}
bool queue::isEmpty(){
    return m_tail == m_start;
}


int  queue::size(){
    return m_length;
}

int main(){
    queue q;
    for (int i = 0; i < 10; ++i){
        q.push(i);
    }

    cout << "queue first is: " << q.front() << endl;
    cout << "queue last is:  " << q.back() << endl;

    for (int i = 0; i < 10; ++i){
        cout << "queue first is: " << q.front() << ends << "queue size is:  " << q.size() << endl;
        q.pop();
    }
    cout << "queue is empty: " << q.isEmpty() << endl;
    for (int i = 0; i < 10; ++i){
        q.push(i);
    }

    cout << "queue first is: " << q.front() << endl;
    cout << "queue last is:  " << q.back() << endl;
    return 0;
}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值