【数据结构】栈的队列的实现

今天,再次实现一下数据结构中的栈和队列

这次我们用的是C++实现栈和队列,用到了C++多态的一种特性:泛型编程--模板

关于模板这个知识点,我们之前讲过,这次就不多说了

Stack.h

#pragma once

#include<iostream>
using namespace std;
#include<assert.h>

template<typename T>
class Stack
{
public:
	Stack()
		:_p(NULL),_size(0),_capacity(0)
	{}
	~Stack()
	{
		if (_p != NULL)
		{
			delete _p;
			_p = NULL;
			_size = _capacity = 0;
		}
	}
	void Push(const T& t)
	{
		CheckCapacity();
		_p[_size++] = t;
	}
	void Pop()
	{
		assert(_size);
		--_size;
	}
	T& Top()
	{
		return _p[_size - 1];
	}
	const T& Top()const
	{
		return _p[size - 1];
	}
	size_t Size()
	{
		return _size;
	}
	bool Empty()
	{
		return _size == 0;
	}
protected:
	T *_p;
	size_t _size;
	size_t _capacity;
	void CheckCapacity()
	{
		if (_size >= _capacity)
		{
			size_t NewCapacity = _capacity * 2 + 3;
			T* tmp = new T[NewCapacity];
			for (size_t idx = 0; idx < _capacity; ++idx)
			{
				tmp[idx] = _p[idx];
			}
			delete[] _p;
			_p = tmp;
			_capacity = NewCapacity;
		}
	}
};

Queue.h

#pragma once

#include<iostream>
using namespace std;

#include<assert.h>

template<typename T>
struct QueueNode
{
	T* _value;
	QueueNode* next;

	QueueNode(const T& t)
		:_value((T*)t),next(NULL)
	{}
};

template<typename T>
class Queue
{
	typedef QueueNode<T> Node;
public:
	Queue()
		:_head(NULL),_tial(NULL)
	{}
	~Queue()
	{
		Node* cur = _head;
		while (cur)
		{
			Node* del = cur;
			cur = cur->next;
			delete[] del;
			del = NULL;
		}
	}
	void Push(const T& t)
	{
		if (_head == NULL)
		{
			_head = new Node(t);
			_tial = _head;
		}
		else
		{
			_tial->next = new Node(t);
			_tial = _tial->next;
			_tial->next = NULL;
		}
	}
	void Pop()
	{
		assert(_head);
		if (_head == _tial)
		{
			delete[] _head;
			_head = _tial = NULL;
		}
		else
		{
			Node* del = _head;
			_head = _head->next;
			delete[] del;
			del = NULL;
		}
	}
	T& Front()
	{
		assert(_head);
		return (T&)_head->_value;
	}
	const T& Front()const
	{
		assert(_head);
		return _head->_value;
	}

	T& Back()
	{
		assert(_tial);
		return _tial->_value;
	}
	const T& Back()const
	{
		assert(_tial);
		return _tial->_value;
	}
	size_t Size()
	{
		size_t count = 0;
		Node* cur = _head;
		while (cur)
		{
			cur = cur->next;
			count++;
		}
		return count;
	}
	bool Empty()
	{
		return _head == NULL;
	}
protected:
	Node*_head;
	Node* _tial;
};

顺便再提一下函数调用的栈帧,它和我们的栈是有相似的地方的。

无论是一个多么复杂的递归程序,我们都可以用非递归实现;

简单的递归可以直接用循环,难一点的递归我们就可以用数据结构中的栈进行实现

相关文章

键树的基本概念 键树又称数字查找树(Digital Search Tree)。 它是一棵度大于等于2的树,树中的每个结...
[TOC] 基本概念 数据: 数据 是对客观事物的符号表示,在计算机科学中指所有能输入到计算机中并被计算机...
[TOC] 反证法 基本概念: 一般地,假设原命题不成立(即 在原命题的条件下,结论不成立),经过正确的推...
最近抽空整理了&quot;数据结构和算法&quot;的相关文章。在整理过程中,对于每种数据结构和算法...
[TOC] 矩阵在计算机图形学、工程计算中占有举足轻重的地位。在数据结构中考虑的是如何用最小的内存空间...
[TOC] 大O表示法:算法的时间复杂度通常用大O符号表述,定义为T[n] = O(f(n))。称函数T(n)以f(n)为界或...