算法9.链式队列
2026/9/19 5:49:39 网站建设 项目流程

算法9.链式队列



// 09_链式队列.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。//#include<iostream>usingnamespacestd;// 链式队列classLinkQueue{public:LinkQueue(){head_=newNode();head_->next_=head_;head_->pre_=head_;}~LinkQueue(){Node*p=head_->next_;while(p!=head_){head_->next_=p->next_;p->next_->pre_=head_;deletep;p=head_->next_;}deletehead_;head_=nullptr;}public:// 入队voidpush(intval){Node*node=newNode(val);node->next_=head_;node->pre_=head_->pre_;head_->pre_->next_=node;head_->pre_=node;}// 出队voidpop(){Node*p=head_->next_;head_->next_=p->next_;p->next_->pre_=head_;deletep;}// 获取队头元素intfront()const{if(head_->next_==head_){throw"queue is empty!";}returnhead_->next_->data_;}// 获取队尾元素intback()const{if(head_->next_==head_){throw"queue is empty!";}returnhead_->pre_->data_;}// 判空boolempty()const{returnhead_->next_==head_;}private:structNode{Node(intdata=0):data_(data),next_(nullptr),pre_(nullptr){}intdata_;Node*next_;Node*pre_;};Node*head_;// 指向头节点};intmain(){intarr[]={12,4,56,7,89,31,53,75};LinkQueue que;for(intv:arr){que.push(v);}cout<<que.front()<<endl;cout<<que.back()<<endl;que.push(100);que.push(200);que.push(300);cout<<que.front()<<endl;cout<<que.back()<<endl;while(!que.empty()){cout<<que.front()<<" "<<que.back()<<endl;que.pop();}}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询