头文件
#include<stdio.h>
#include<stdbool.h>
#include<assert.h>
typedef int QdataTyped;
typedef struct QueueNode
{
struct QueueNode *next;
QdataTyped data;
}QueueNode;
typedef struct Queue
{
struct QueueNode *head;
struct QueueNode *tail;
}Queue;
void QueueInit(Queue *pq);
void QueueDestory(Queue *pq);
void QueuePush(Queue *pq, QdataTyped x);
void QueuePop(Queue *pq);
QdataTyped QueueFront(Queue *pq);
QdataTyped Queueback(Queue *pq);
bool QueueEmpty(Queue *pq);
int QueueSize(Queue *pq);
实现
#include"queue.h"
void QueueInit(Queue *pq)
{
pq->head = NULL;
pq->tail = NULL;
}
void QueueDestory(Queue *pq)
{
QueueNode *cur = pq->head;
while (cur != NULL)
{
QueueNode *next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
void QueuePush(Queue *pq, QdataTyped x)
{
assert(pq);
QueueNode *newnode = (QdataTyped *)malloc(sizeof(QueueNode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
if (QueueEmpty(pq))
{
pq->head = pq->tail = newnode;
}
else{
(pq->tail)->next = newnode;
pq->tail = newnode;
}
}
void QueuePop(Queue *pq)
{
assert(pq);
assert(!QueueEmpty(pq));
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QueueNode *next = pq->head->next;
free(pq->head);
pq->head = next;
}
}
QdataTyped QueueFront(Queue *pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
QdataTyped Queueback(Queue *pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
bool QueueEmpty(Queue *pq)
{
return pq->head == NULL;
}
int QueueSize(Queue *pq)
{
int size = 0;
QueueNode *cur = pq->head;
while (cur != NULL)
{
size++;
cur = cur->next;
}
return size;
}
|