手动实现队列
#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;
}