C++实现栈和队列

栈的实现

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


template <class T>
class stack
{
private:
	T* p;
	int _size;
	int _capacity;
public:
	stack() :p(NULL), _size(0), _capacity(0) { ; }
	~stack() { delete[]p; _size = 0; _capacity = 0; }
	void Checkcapacity()
	{
		if (_size == _capacity)
		{
			T* newp = new T[_capacity == 0 ? 4 : _capacity * 2];
			for (int i = 0; i < _size; i++)
			{
				newp[i] = p[i];
			}
			delete[]p;
			p = newp;
			_capacity = _capacity == 0 ? 4: _capacity * 2;
		}
	}
	// 入栈
	void push(T val)
	{
		Checkcapacity();
		p[_size++] = val;
	}
	// 获取栈顶元素
	T top()
	{
		assert(_size);
		return p[_size - 1];
	}
	// 出栈
	T pop()
	{
		assert(_size);
		_size--;
		return p[_size];
	}
	// 检测栈是否为空 
	bool empty()
	{
		return _size == 0;
	}
	// 获取栈中有效元素个数
	int size() { return _size; }
	int capacity() { return _capacity; }
};

由于是由C++中的模板实现的所以将函数的实现放在了类的里面,技术有限还请见谅,

队列也是一样。

队列的实现

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


template <class T>
class Node
{
public:
	T val;
	Node<T>* next;
	Node(T v) :val(v) ,next(NULL){ ; }
};

template<class T> 
class queue
{
private:
	Node<T>* head;
	Node<T>* tail;
	int num;
public:
	queue() {
		head = new Node<T>(0);
		tail = head;
		num = 0;
	}
	// 队尾入队列
	void push(T val) {

		Node<T>* newnode = new Node<T>(val);
		// 用来进行判空
		assert(newnode);
		tail->next = newnode;
		tail = newnode;
		num++;
	}
	// 队头出队列 
	T pop()
	{
		assert(num);
		Node<T>* cur = head->next;
		head->next = cur->next;
		T top = cur->val;
		delete cur;
		num--;
		return top;
	}
	// 获取队列头部元素 
	T front()
	{
		assert(num);
		return head->next->val;
	}
	// 获取队列队尾元素 
	T back()
	{
		assert(num);
		return tail->val;
	}
	// 获取队列中有效元素个数 
	int size() { return num; }
	// 检测队列是否为空,如果为空返回非零结果,如果非空返回0 
	bool empty()
	{
		return num == 0;
	}

	~queue(){
		Node<T>* cur = head;
		while (cur != NULL)
		{
			head = head->next;
			delete cur;
			cur = head;
		}
		num = 0;
	}
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值