在一个缓冲去内实现三个栈,使用自有链表记录空闲块

#include<iostream>
#include<iomanip>
#include<list>
#include<cmath>
#include<vector>
#include<assert.h>
#include"Test.h"
#include<set>
#include<stack>
using namespace std;


char *buffer=new char[24];
int len=24;
template<class T>
class CStack
{
    struct Node
    {
        Node *next;
        T value;
    public:
        Node():next(NULL){}
    };
    void *freehead;
    Node *shead[3];
    void IntialFreeList()
    {
        freehead=buffer;
        char *p=buffer;
        int size=sizeof(Node);
        while(p+size<=buffer+len)
        {
            if(p+2*size<=buffer+len)
                ((Node*)p)->next=(Node*)(p+size);
            else
              ((Node*)p)->next=NULL;
            p+=size;
        }
        if(size>len)
            freehead=NULL;
        else
            freehead=buffer;
    }
    Node *GetNode()
    {
        Node *p=NULL;
        void *pTemp;
        if(freehead!=NULL)
        {
            pTemp=freehead;
            freehead=(char*)((Node*)freehead)->next;
            p=new (pTemp) Node();
        }
        return p;
    }
    void AddNode(Node *p)
    {
        p->~Node();
        if(freehead==NULL)
        {
            ((Node*)p)->next=NULL;
            freehead=(char*)p;
        }
        else
        {
            ((Node*)p)->next=(Node*)freehead;
            freehead=p;
        }
    }
public:
    
    CStack()
    {
        int i;
        for(i=0;i<3;i++)shead[i]=NULL;
        IntialFreeList();
    }
    void push(int num,T t)
    {
        Node *p=GetNode();
        if(p!=NULL)
        {
                p->value=t;
                p->next=shead[num];
                shead[num]=p;
        }
        else
        {
            throw exception("Space is not enough");
        }
    }
    void pop(int num)
    {
        Node * &h=shead[num];
        if(h!=NULL)
        {
            Node *p=h;
            h=h->next;
            AddNode(p);
        }
    }
    T top(int num)
    {
        Node *h=shead[num];
        if(h!=NULL)
        {
            return h->value;
        }
    }
};

void main()
{


    CStack<int> s;
    s.push(0,0);
    s.push(1,1);
    s.push(2,2);
    
    s.pop(2);
    s.pop(0);
    s.pop(1);
    system("pause");
}

 

posted on 2013-07-29 14:58  dyc0113  阅读(215)  评论(0编辑  收藏  举报

导航