#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
typedef unsigned char uint8_t;
typedef struct QListNode
{
struct QListNode* next;
uint8_t type;
uint8_t* data;
}QNode;
typedef struct Queue
{
QNode* front;
QNode* rear;
int size;
}Queue;
//初始化队列
void QueueInit(Queue* q);
//队尾入队列
void QueuePush(Queue* q, uint8_t* data);
//队头出队列
void QueuePop(Queue* q);
//获取队列头部元素
uint8_t* QueueFront(Queue* q);
//获取队列队尾元素
uint8_t* QueueRear(Queue* q);
//获取队列中有效元素个数
int QueueSize(Queue* q);
//检测队列是否为空
int QueueEmpty(Queue* q);
//销毁队列
void QueueDestory(Queue* q);
//初始化队列
void QueueInit(Queue* q)
{
assert(q);
q->front = q->rear = NULL;
q->size = 0;
}
//队尾入队列
void QueuePush(Queue* q, uint8_t* data)
{
assert(q);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
else
{
newnode->data = data;
newnode->next = NULL;
}
if (q->rear == NULL)
{
q->front = q->rear = newnode;
}
else {
q->rear->next = newnode;
q->rear = newnode;
}
}
//队头出队列
void QueuePop(Queue* q)
{
assert(q);
assert(!QueueEmpty(q));
if (q->front->next == NULL)
{
free(q->front);
q->front = q->rear = NULL;
}
else {
QNode* del = q->front;
q->front = q->front->next;
free(del);
del = NULL;
}
q->size--;
}
//获取队列头部元素
uint8_t* QueueFront(Queue* q)
{
assert(q);
return q->front->data;
}
//获取队列队尾元素
uint8_t* QueueRear(Queue* q)
{
assert(q);
return q->rear->data;
}
//获取队列中有效元素个数
int QueueSize(Queue* q)
{
assert(q);
return q->size;
}
//检测队列是否为空
int QueueEmpty(Queue* q)
{
assert(q);
return q->rear == NULL;
}
//销毁队列
void QueueDestory(Queue* q)
{
assert(q);
QNode* cur = q->front;
while (cur)
{
QNode* del = cur;
free(del);
del = NULL;
cur = cur->next;
}
}
/**
* Function : printQueue
* Description : 打印队列所有元素
* Input :
*
* Output :
* Return :
* Auther : zhaoning
* Others :
**/
void printQueue(QNode* head)
{
while (head != NULL)
{
printf("%d ", *head->data);
head = head->next;
}
printf("\n");
}
int main()
{
Queue q;
uint8_t a = 1;
uint8_t b = 5;
uint8_t c = 9;
uint8_t d = 7;
uint8_t e = 100;
uint8_t f = 128;
uint8_t g = 11;
uint8_t h = 19;
uint8_t i = 99;
QueueInit(&q);
QueuePush(&q, &a);
QueuePush(&q, &b);
QueuePush(&q, &c);
QueuePush(&q, &d);
QueuePush(&q, &e);
QueuePush(&q, &f);
QueuePush(&q, &g);
QueuePush(&q, &h);
QueuePush(&q, &i);
printQueue(q.front);
printf("\n");
while (!QueueEmpty(&q))
{
//printf("%d\n", *QueueFront(&q));
QueuePop(&q);
printQueue(q.front);
printf("\n");
}
QueueEmpty(&q);
printf("\n");
return(0);
}
$gcc -o main *.c -lm
$main
1 5 9 7 100 128 11 19 99
5 9 7 100 128 11 19 99
9 7 100 128 11 19 99
7 100 128 11 19 99
100 128 11 19 99
128 11 19 99
11 19 99
19 99
99