自己實現的stack模板類

之所以要自己實現這個類,基於如下兩點原因:
1、C++標準庫裏的stack模板類,實現得過於複雜,用起來也不方便;
2、爲了改進文件夾遍歷算法——改遞歸爲循環。

#ifndef HSW_STACK_H_
#define HSW_STACK_H_

/*
如下模板類使用單鏈表實現了棧類型 zhujw 2017.3.1
*/

#ifndef __cplusplus
typedef unsigned char bool ;
#endif

#ifndef NULL
#define NULL (void*)0
#endif

#ifndef tbool
typedef char tbool,*ptbool;
#endif

typedef struct tagStackNode
{
    struct tagStackNode *Next;

    tagStackNode()
    {
        Next = NULL;
    }

}HSW_STACK_NODE,*PHSW_STACK_NODE,HSW_STACK_NODE_ENTRY,*PHSW_STACK_NODE_ENTRY;


#define HswInitializeStack(listhead)\
    ((listhead)->Next = NULL)

#define HswIsStackEmpty(listhead)\
    ((listhead)->Next == NULL)

#define PushEntryList(listhead,entry)\
    (entry)->Next = (listhead)->Next;\
    (listhead)->Next = (entry)

#define PopEntryList(listhead) \
    (listhead)->Next;\
{\
    PHSW_STACK_NODE_ENTRY FirstEntry;\
    FirstEntry = (listhead)->Next;\
    if (FirstEntry != NULL)      \
{(listhead)->Next = FirstEntry->Next;}}                        


#define __list_for_each_stack_node(Entry, Listhead) \
    for (Entry = (Listhead)->Next; Entry != NULL; Entry = Entry->Next)

template <class T>
class HswStack
{
public:
    typedef struct tagClassTemplate
    {
        HSW_STACK_NODE Link;
        T              data;
    }Node,*PNode;
    HswStack()
    {
        HswInitializeStack(&m_list_head);
        m_icount = 0;
    }
    virtual ~HswStack()
    {
        free();
    }
public:
    int size(){return m_icount;}
    void push(const T& n)
    {
        PNode node = new Node;
        node->data = n;
        PushEntryList(&m_list_head,&node->Link);
        m_icount++;
    }
    tbool pop(T& n)
    {
        if (HswIsStackEmpty(&m_list_head))
        {
            return 0;
        }
        PNode node = (PNode)PopEntryList(&m_list_head);
        n = node->data;
        delete node;
        m_icount--;
        return 1;
    }
    void free()
    {
        PNode n;

        while (!HswIsStackEmpty(&m_list_head))
        {
            n = (PNode)PopEntryList(&m_list_head);
            delete n;           
        }
        m_icount=0;
    }
    T* operator[](int index)const
    {
        if (index < 0 || index >= m_icount)
        {
            return NULL;
        }
        PHSW_STACK_NODE pos;
        int i=0;
        __list_for_each_stack_node(pos,&m_list_head)
        {
            if (i == index)
            {
                T* ret = &((PNode)pos)->data;
                return ret;
            }
            i++;
        }
        return NULL;
    }
    T* begin()const
    {
        return (*this)[0];
    }
    T* end()const
    {
        if (m_icount > 0)
        {
            return (*this)[m_icount-1];
        }
        else
            return NULL;
    }

private:
    HSW_STACK_NODE m_list_head;
    int m_icount;
};

#endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章