动态数组实现队列

#pragma once 

template<class T>
class Queue
{
	struct Node
	{
		T _data;
		Node *_next;

		Node(const T&x)
			:_data(x)
			, _next(NULL)
		{}
	};
public:
	Queue()
		:_head(NULL)
		, _tail(NULL)
		, _size(0)
	{}

	~Queue()
	{
		while (_head != NULL)
		{
			Node *tmp = _head;
			_head = _head->_next;
			delete tmp;
		}
		_head = _tail = NULL;
		_size = 0;
	}

	void push(const T&x)
	{
		if (_head == NULL)
		{
			_head = new Node(x);
			_tail = _head;
		}
		else
		{
			_tail->_next = new Node(x);
			_tail = _tail->_next;
		}
		++_size;
	}

	void pop()
	{
		assert(_head);//注意检查
		//考虑到只有一个节点 将两个指针置空
		if (_head == _tail)
		{
			delete _head;
			_head = NULL;
			_tail = NULL;
		}
		else
		{
			Node *tmp = _head;
			_head = _head->_next;
			delete tmp;
		}
		--_size;
	}

	const T& front()
	{
		if (_size != 0)
			return _head->_data;
	}

	const T& back()
	{
		if (_size != 0)
			return _tail->_data;
	}

	inline size_t size(){ return _size; }
	inline bool empty(){ return _size == 0; }

	void Print()
	{
		Node *newHead = _head;           //千万考虑到对队列的修改
		while (newHead != _tail->_next)  //打印的时候认准条件
		{
			cout << newHead->_data<<" ";
			newHead = newHead->_next;
		}
		printf("\n");
	}
private:
	Node *_head;
	Node *_tail;
	size_t _size;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值