C++类模板实现队列(链表实现)

  1. 使用链表保存数据
  • 头文件如下
#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();

	}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值