操作代码(入队 ,出队等)
typedef int ElemType;
typedef struct QNode{
ElemType data;
struct QNode *next;
}QDataNode;
typedef struct{
int count;
QDataNode *front;
QDataNode *rear;
}QHeadNode,*LinkQueue;
#define MEM_ALLOC_FAIL 1
#define QUEUE_NOT_EXISTS 2
#define QUEUE_EMPTY 3
#define LINE_DATA_NUMS 4
int InitQueue(LinkQueue *Q);
int EnQueue(LinkQueue *Q,ElemType elem);
int DeQueue(LinkQueue *Q,ElemType *elem);
int ClearQueue(LinkQueue *Q);
int DestroyQueue(LinkQueue *Q);
int QueueLength(LinkQueue Q);
int QueueEmpty(LinkQueue Q);
int GetQHead(LinkQueue Q,ElemType *elem);
int QTraverse(LinkQueue Q,void (*visit)(ElemType elem));
void Output(ElemType elem);
//依据实际数据类型进行修改
void Output(ElemType elem)
{
printf("%d",elem);
}
int InitQueue(LinkQueue *Q)
{
LinkQueue qhead = (LinkQueue)malloc(sizeof(QHeadNode));
QDataNode *vhead = (QDataNode *)malloc(sizeof(QDataNode));
if(qhead == NULL || vhead == NULL)
{
return MEM_ALLOC_FAIL;
}
vhead->next = NULL; //虚设数据头节点next指针域设置为NULL
*Q = qhead;
(*Q)->front = vhead;
(*Q)->rear = vhead;
(*Q)->count = 0;
return 0;
}
int EnQueue(LinkQueue *Q,ElemType elem)
{
if(*Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
QDataNode *dptr = (QDataNode *)malloc(sizeof(QDataNode));
if(dptr == NULL)
{
return MEM_ALLOC_FAIL;
}
dptr->data = elem;
dptr->next = NULL;
(*Q)->rear->next = dptr;
(*Q)->rear = dptr;
(*Q)->count += 1;
return 0;
}
int DeQueue(LinkQueue *Q,ElemType *elem)
{
if(*Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
if(QueueEmpty(*Q) == 1)
{
return QUEUE_EMPTY;
}
QDataNode *dptr = (*Q)->front->next;
*elem = dptr->data;
(*Q)->front->next = dptr->next;
if(dptr == (*Q)->rear)
{
(*Q)->rear = (*Q)->front;
}
free(dptr);
(*Q)->count -= 1;
return 0;
}
int QueueLength(LinkQueue Q)
{
if(Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
return Q->count;
}
int QueueEmpty(LinkQueue Q)
{
if(Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
if(Q->count == 0)
{
return 1;
}
return 0;
}
int GetQHead(LinkQueue Q,ElemType *elem)
{
if(Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
if(QueueEmpty(Q) == 1)
{
return QUEUE_EMPTY;
}
*elem = Q->front->next->data;
return 0;
}
int ClearQueue(LinkQueue *Q)
{
if(*Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
while((*Q)->count != 0)
{
QDataNode *dptr = (*Q)->front->next;
(*Q)->front->next = dptr->next;
if(dptr == (*Q)->rear)
{
(*Q)->rear = (*Q)->front;
}
free(dptr);
(*Q)->count -= 1;
}
return 0;
}
int DestroyQueue(LinkQueue *Q)
{
if(*Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
while((*Q)->front != NULL)
{
(*Q)->rear = (*Q)->front->next;
free((*Q)->front);
(*Q)->front = (*Q)->rear;
}
free(*Q);
*Q = NULL;
return 0;
}
int QTraverse(LinkQueue Q,void (*visit)(ElemType elem))
{
if(Q == NULL)
{
return QUEUE_NOT_EXISTS;
}
if(QueueEmpty(Q) == 1)
{
return QUEUE_EMPTY;
}
QDataNode *ptr = Q->front->next;
for(int i = 0; i < Q->count; i++)
{
(*visit)(ptr->data);
printf("\t");
ptr = ptr->next;
if((i+1) % LINE_DATA_NUMS == 0)
{
printf("\n");
}
}
printf("\n");
return 0;
}