加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 05:56:10 所属栏目:安全 来源:网络整理
导读:今天,再次实现一下数据结构中的栈和队列 这次我们用的是C++实现栈和队列,用到了C++多态的一种特性:泛型编程--模板 关于模板这个知识点,我们之前讲过,这次就不多说了 Stack.h #pragma once#includeiostreamusing namespace std;#includeassert.htemplate

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

这次我们用的是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;
};

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读