自己实现的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

你可能感兴趣的:(源码)