#ifndef HSW_QUEUE_H_
#define HSW_QUEUE_H_
/*
如下模板类使用单链表实现了队列类型 zhujw 2017.3.2
*/
#ifndef __cplusplus
typedef unsigned char bool ;
#endif
#ifndef NULL
#define NULL (void*)0
#endif
#ifndef tbool
typedef char tbool,*ptbool;
#endif
typedef struct tagSingleList
{
struct tagSingleList *Next;
tagSingleList()
{
Next = NULL;
}
}HSW_SINGLE_LIST,*PHSW_SINGLE_LIST,HSW_SINGLE_LISE_ENTRY,*PHSW_SINGLE_LIST_ENTRY;
typedef struct tagQueue
{
HSW_SINGLE_LISE_ENTRY *Front;
HSW_SINGLE_LISE_ENTRY *Rear;
tagQueue()
{
Rear = NULL;
Front = NULL;
}
}HSW_QUEUE_POINTER,*PHSW_QUEUE_POINTER,HSW_QUEUE_ENTRY,*PHSW_QUEUE_ENTRY;
#define HswInitializeQueue(listhead)\
((listhead)->Rear = (listhead)->Front = NULL)
#define HswIsQueueEmpty(listhead)\
((listhead)->Front == NULL)
#define PushEntry(listhead,entry)\
if((listhead)->Front == NULL)\
{(listhead)->Front = (entry);(listhead)->Rear = (entry);}\
else\
{(listhead)->Rear->Next = (entry);(listhead)->Rear = (entry);}
#define PopEntry(listhead) \
(listhead)->Front;\
{\
PHSW_SINGLE_LIST_ENTRY Entry;\
Entry = (listhead)->Front;\
if(Entry != NULL)\
{(listhead)->Front = Entry->Next;}}
#define __list_for_each_queue_node(Entry, Listhead) \
for (Entry = (Listhead)->Front; Entry != NULL; Entry = Entry->Next)
template <class T>
class HswQueue
{
public:
typedef struct tagClassTemplate
{
HSW_SINGLE_LIST Link;
T data;
}Node,*PNode;
HswQueue()
{
HswInitializeQueue(&m_list_head);
m_icount = 0;
}
virtual ~HswQueue()
{
free();
}
public:
int size(){return m_icount;}
void push(const T& n)
{
PNode node = new Node;
node->data = n;
PushEntry(&m_list_head,&node->Link);
m_icount++;
}
tbool pop(T& n)
{
if (HswIsQueueEmpty(&m_list_head))
{
return 0;
}
PNode node = (PNode)PopEntry(&m_list_head);
n = node->data;
delete node;
m_icount--;
return 1;
}
void free()
{
PNode n;
while (!HswIsQueueEmpty(&m_list_head))
{
n = (PNode)PopEntry(&m_list_head);
delete n;
}
m_icount=0;
}
T* operator[](int index)const
{
if (index < 0 || index >= m_icount)
{
return NULL;
}
PHSW_SINGLE_LIST pos;
int i=0;
__list_for_each(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_QUEUE_POINTER m_list_head;
int m_icount;
};
#endif
以上代码实现了queue,即队列。queue是最简单的数据结构之一,就像我们排队一样,队列中的数据只能从一端进,另一端出;但为了扩展它的功能,提供了下标访问方式。要使用它,非常简单。如下代码示意了如何使用它。
HswQueue<int> m_int_list;
for(int i=1;i<=10;i++)
{
m_int_list.push(i);
}
printf("m_int_list[8]=%d\n",m_int_list[8]);
int j;
while(m_int_list.pop(j))
{
printf("%d\n",j);
}
程序输出结果如下:
8
1
2
3
4
5
6
7
8
9
10