- 使用链表保存数据
#pragma once
template <class T>
class LinkQueue
{
public:
LinkQueue();
~LinkQueue();
bool IsEmpty();
size_t Size();
void Push(const T&);
void Pop();
void Clear();
T& Front() const;
private:
struct LinkNode
{
T data;
LinkNode* next;
LinkNode(const T& item, LinkNode* link = nullptr) :data(item), next(link) {};
};
LinkNode* m_front;
LinkNode* m_back;
size_t m_size;
};
template<class T>
inline LinkQueue<T>::LinkQueue()
:m_front(0), m_back(0), m_size(0)
{
}
template<class T>
inline LinkQueue<T>::~LinkQueue()
{
Clear();
}
template<class T>
inline bool LinkQueue<T>::IsEmpty()
{
return m_front == nullptr;
}
template<class T>
inline size_t LinkQueue<T>::Size()
{
return m_size;
}
template<class T>
inline void LinkQueue<T>::Push(const T& item)
{
if (IsEmpty())
{
m_front = m_back = new LinkNode(item);
}
else
{
m_back->next = new LinkNode(item);
m_back = m_back->next;
}
m_size++;
}
template<class T>
inline void LinkQueue<T>::Pop()
{
LinkNode* tem = m_front;
m_front = m_front->next;
delete tem;
m_size--;
}
template<class T>
inline void LinkQueue<T>::Clear()
{
while (!IsEmpty())
{
Pop();
}
}
template<class T>
inline T& LinkQueue<T>::Front() const
{
return m_front->data;
}
LinkQueue<int> queue;
for (size_t i = 0; i < 21; i++)
{
queue.Push(i);
}
while (!queue.IsEmpty())
{
cout << queue.Front() << " size:" << queue.Size() << endl;
queue.Pop();
}
for (size_t i = 0; i < 11; i++)
{
queue.Push(i*10 + 1);
}
while (!queue.IsEmpty())
{
cout << queue.Front() << " size:" << queue.Size() << endl;
queue.Pop();
}