#pragma once
//===================链队===================
/*链队列是基于链表实现的队列:链表头部为队首,链表尾部为队尾*/
template<typename T>
struct QueueNode
{
T value;
QueueNode<T> *next;
struct QueueNode(T x) :value(x), next(nullptr){};
};
template<typename T>
class LinkQueue
{
public:
LinkQueue();
~LinkQueue();
bool isEmpty();
int size();
bool mypop();
void mypush(T t);
T front();
private:
QueueNode<T> *phead;
QueueNode<T> *pend;
int count;
};
template<typename T>
LinkQueue<T>::LinkQueue()
{
phead = new QueueNode<T>(0);
pend = phead;
count = 0;
}
template<typename T>
LinkQueue<T>::~LinkQueue()
{
while (phead->next != nullptr)
{
QueueNode<T> *tmpNode = phead;
phead = phead->next;
delete tmpNode;
}
}
template<typename T>
bool LinkQueue<T>::isEmpty()
{
return count == 0;
}
template<typename T>
int LinkQueue<T>::size()
{
return count;
}
//队尾插入
template<typename T>
void LinkQueue<T>::mypush(T t)
{
QueueNode<T> *tmpNode = new QueueNode<T>(t);
pend->next = tmpNode;
pend = tmpNode;
count++;
}
//在队首删除
template<typename T>
bool LinkQueue<T>::mypop()
{
if (count == 0)
{
cout << "空队" << endl;
return false;
}
else
{
QueueNode<T> *tmpNode = phead->next;
phead->next = phead->next->next;
delete tmpNode;
return true;
}
}
//获取队首元素
template<typename T>
T LinkQueue<T>::front()
{
if (count == 0)
{
cout << "空队" << endl;
return false;
}
else
return phead->next->value;
}
int main()
{
//==========链队===========
LinkQueue<int> *lqueue = new LinkQueue<int>();
int n;
while (cin >> n)
lqueue->mypush(n);
cout << "队列大小:" << lqueue->size() << endl;
while (!lqueue->isEmpty())
{
cout << lqueue->front() << " ";
lqueue->mypop();
}
cout << endl;
}
链队列的基本操作(C++)
最新推荐文章于 2022-11-23 19:54:56 发布