9.25 C++继承 多态

手动实现队列

#include <iostream>

using namespace std;

class My_queue
{
private:
    struct Node //队列结构体
    {
        int data;
        Node *next;
        Node(int value):data(value),next(nullptr){}
    };

    Node *front;
    Node *rear;
    int size;

public:
    My_queue():front(nullptr),rear(nullptr),size(0){}
    ~My_queue()
    {
        while(!empty())
        {
            pop();
        }
    }

    bool empty() //判空
    {
        return size==0;
    }

    int get_front()//获取队首
    {
        if(empty())
        {
            throw std::out_of_range("队列为空");
        }
        return front->data;
    }

    int get_rear()//获取队尾
    {
        if(empty())
        {
            throw std::out_of_range("队列为空");
        }
        return rear->data;
    }

    void push(int value) //入队
    {
        Node *temp=new Node(value);
        if(empty())
        {
            front=rear=temp;
        }else
        {
            rear->next=temp; //链接到队列的末尾
            rear=temp; //更新为指向新节点
        }
        size++;
    }

    int pop()//出队
    {
        if(empty())
        {
            throw std::out_of_range("队列已空");
        }
        Node *temp=front;  //储存队首节点
        int value=front->data; //提取队首数据
        front=front->next;  //断开队首链接
        delete temp;  //释放temp节点
        size--;
        if(empty())
        {
            rear=nullptr;
        }
        return value; //返回队首数据
    }



    My_queue &operator=(const My_queue &other)
    {
        if(this!=&other)//检查自我赋值
        {
            while (!empty()) //清空队列
            {
                pop();
            }
            Node *temp=other.front;
            while (temp) //遍历other队列
            {
                push(temp->data);
                temp=temp->next;
            }
        }
        return *this;
    }

    int get_size()
    {
        return this->size;
    }


};

int main()
{
    My_queue q;
    q.push(3);
    q.push(4);
    q.push(5);
    q.push(6);

    cout<<"队首= "<<q.get_front()<<endl;
    cout<<"队尾= "<<q.get_rear()<<endl;

    cout<<"出队:"<<q.pop()<<endl;
    cout<<"出队后队首= "<<q.get_front()<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值