QueueByList.h
#ifndef _QUEUE_H
typedef struct Node * PtrNode;
typedef struct QueueByList * PtrQueueByList;
PtrQueueByList CreateQueue();
bool IsEmpty(PtrQueueByList Q);
void EnQueue(PtrQueueByList Q,int X);
int DeQueue(PtrQueueByList Q);
void DeleteQueue(PtrQueueByList Q);
#endif //_QUEUE_H
struct QueueByList
{
PtrNode frontQ;
PtrNode rearQ;
};
struct Node
{
int m_value;
PtrNode m_next;
};
QueueByList.cpp
#include "StdAfx.h"
#include "QueueByList.h"
PtrQueueByList CreateQueue()
{
PtrQueueByList Q = NULL;
Q = new QueueByList();
Q->frontQ = NULL;
Q->rearQ = NULL;
return Q;
}
bool IsEmpty(PtrQueueByList Q)
{
if (Q->frontQ == NULL && Q->rearQ == NULL)
return true;
else
return false;
}
void EnQueue(PtrQueueByList Q,int X)
{
PtrNode P = NULL;
P = new Node();
P->m_value = X;
if (IsEmpty(Q))
Q->frontQ = Q->rearQ = P;
else
{
Q->rearQ->m_next = P;
Q->rearQ = P;
}
}
int DeQueue(PtrQueueByList Q)
{
if (IsEmpty(Q))
throw "Empty queue!";
else
{
//到了最后一个节点出列时,需要处理rear指针
//否则该节点出列并删除之后,rear指针悬垂
//同时也为了保持队列为空的判断条件
if (Q->frontQ == Q->rearQ)
Q->rearQ = NULL;
int X = Q->frontQ->m_value;
PtrNode P = Q->frontQ->m_next;
delete Q->frontQ;//别忘了删除节点
Q->frontQ = P;
return X;
}
}
void DeleteQueue(PtrQueueByList Q)
{
while (!IsEmpty(Q))
DeQueue(Q);
}