C++ 用链表实现队列(queue)

本文详细探讨如何使用C++通过链表数据结构实现队列操作,包括入队、出队以及相关算法的实现,适用于xcode开发环境,深入理解数据结构中的队列概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<cstring>
#include<cstdlib>
#include"Header.h"

using namespace std;

template<typename type>
class Node
{
   public:
   Node *next;
   type element;
   Node(const type& it,Node *nextValue)
 {
    element=it;
    next=nextValue;
 }
    Node(Node *nextValue)
   {
   next=nextValue;
   }
  Node(){}
  ~Node(){}
};

template<typename type>
class Lqueue:public Queue<type>
{
private:
Node<type>* front;
Node<type>* rear;
int nodeNum;

public:
Lqueue()
{
front=rear=new Node<type>();
nodeNum=0;
}
~Lqueue()
{
clear();
delete front;
}
void clear()
{
while(front->next!=NULL)
{
rear=front;
front=front->next;
delete rear;
}
rear=front;
nodeNum=0;
}
bool isEmpty()
{
if(front->next==NULL)
cout<<"The queue is empty."<<endl;
return 0;
}
bool isFull()
{
Node<type>* temp=new Node<type>(NULL);
if(temp==NULL)
{
cout<<"The queue is full."<<endl;
return true;
}
return false;
}
void enqueue(type& a)
{
rear->next = new Node<type>(a,NULL);
rear=rear->next;
nodeNum++;
}
type dequeue()
{
type temp;
temp=front->next->element;
Node<type>* pointer=front->next;
front->next=pointer->next;
if(rear==pointer)
{
rear=front;
}
delete pointer;
nodeNum--;
return temp;
}
const type& frontValue()
{
return front->next->element;
}
int length()
{
return nodeNum;
}

};


int main()
{
Lqueue<int> a;
for(int i=0;i<5;i++)
{
int value;
cin>>value;
a.enqueue(value);
}
cout<<endl;
a.dequeue();
cout<<a.frontValue()<<endl;
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值