C++——内存池(链式栈)

Mstack.h

#ifndef MSTACK_H
#define MSTACK_H

#include <iostream>
using namespace std;
#define LEN 10

template<typename T>
class Mstack
{
public:
	class Node;
	Mstack() //构造函数
	{
		_top = new Node();
		_head = _top;
		_len = 0;
	}

	~Mstack()
	{
		while(!isEmpty())
		{
			Node* p = _head;
			_head = _head->_next;
			delete p;
			_len--;
		}
	}

	void push(T val)
	{
		_top->_val = val;
		_top->_next = new Node(val);
		_top = _top->_next;
		_len++;
	}

	void pop()
	{
		if(isEmpty())
		{
			throw "stack is empty";
		}
		Node* p = _head;
		while(p->_next != _top)
		{
			p = p->_next;
		}
		delete _top;
		_top = p;
		_len--;
	}

	T top()
	{
		Node *p = _head;
		while(p->_next != _top)
		{
			p = p->_next;
		}
		return p->_val;
	}

	bool isEmpty()
	{
		if(_len == 0)
		{
			return true;
		}
		return false;
	}

private:
	class space
	{
	public:
		static space* getSpace()
		{
			if(_space == NULL)
			{
				//m.lock()
				if(_space == NULL)
				{
					_space = new space();
				}
				//m.unlock()
			}
			return _space;
		}

	private:
		space()
		{
			Node *tmp = new Node[LEN];
			int i = 0;
			for(; i<LEN-1; i++)
			{
				tmp[i]._next = &tmp[i+1];
			}
			tmp[i]._next = NULL;
			_pool = &tmp[0];
		}
		static space* _space;
		Node* _pool;
		friend class Node;
	};

	class Node
	{
	private:
		T _val;
		Node* _next;
		static space* _space;
	public:
		Node()
		{
			_next = NULL;
		}

		Node(T val)
		{
			_val = val;
			_next = NULL;
		}

		void *operator new(size_t size)
		{
			cout<<"void *operator new(size_t size)"<<endl;
			//if(_space->_pool == NULL)
			//m.lock()
			if(_space->_pool == NULL)
			{
				Node* tmp = new Node[LEN];
				int i = 0;
				for(; i<LEN-1; i++)
				{
					tmp[i]._next = &tmp[i+1];
				}
				tmp[i]._next = NULL;
				_space->_pool = &tmp[0];
			}
			//m.unlock()
			Node* mem = _space->_pool;
			_space->_pool = _space->_pool->_next;
			return mem;
		}

		void operator delete(void *p)
		{
			cout<<"void operator delete(void *p)"<<endl;
			Node *tmp = (Node*)p;
			tmp->_next = _space->_pool;
			_space->_pool = tmp;
		}
		friend class Mstack;
	};
	Node* _top;
	Node* _head;
	int _len;
};

template<typename T>
typename Mstack<T>::space* Mstack<T>::Node::_space = Mstack<T>::space::getSpace();

template<typename T>
typename Mstack<T>::space*Mstack<T>::space::_space = NULL;

#endif

main.cpp

#include "Mstack.h"
#include <stack>
int main()
{
	Mstack<int> q1;
	for(int i=0; i<10; i++)
	{
		q1.push(i);
	}
	while(!q1.isEmpty())
	{
		cout<<q1.top()<<"  ";
		q1.pop();
	}
	cout<<endl;

	stack<int> ss;

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值