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;
}