队列的基本操作(c语言版)
队列是数据结构中一种顺序结构,故名思意可以理解为我们日常站队等,先进入队列的数据排在前头,所以先出队列,后进入队列的数据后出队列。而且队列是只能从队尾进入,队头离开,由于出数据只能从队头出,所以选用链表来实现队列更加方便。、
这里将会实现队列的增删以及初始化等基础接口。
先定义一个队列的结构体
typedef int DataType;
typedef struct QueueNode
{
DataType _data;
struct QueueNode* _next;
}QueueNode;
typedef struct Queue
{
QueueNode* _head;
QueueNode* _tail;
}Queue;
对队列进行初始化void QueueInit(Queue* q)
{
q->_head = (QueueNode*)malloc(sizeof(QueueNode));
q->_head->_next = NULL;
q->_tail = q->_head;
}
建立队列结点QueueNode* BuyNewNode(DataType x)
{
QueueNode* q;
q = (QueueNode*)malloc(sizeof(QueueNode));
q->_next = NULL;
q->_data = x;
return q;
}
打印队列void QueuePrint(Queue* q)
{
QueueNode* ptr;
ptr = q->_head->_next;
if (q->_head->_next == NULL)
{
printf("该队列为空!\n");
}
else
{
while (ptr)
{
printf("%d->",ptr->_data);
ptr = ptr->_next;
}
}
printf("NULL");
}
增加数据void QueuePush(Queue* q, DataType x)
{
QueueNode* _new;
if (q->_head ->_next== NULL)
{
q->_tail = BuyNewNode(x);
q->_head->_next = q->_tail;
}
else
{
q->_tail->_next = BuyNewNode(x);
q->_tail = q->_tail->_next;
}
}
删除数据void QueuePop(Queue* q)
{
QueueNode* ptr;
ptr = q->_head->_next;
if (q->_head->_next == 0)
{
printf("该队列为空!\n");
}
else
{
q->_head->_next = q->_head->_next->_next;
free(ptr);
}
}
返回第一个数据DataType QueueFront(Queue* q)
{
return q->_head->_next->_data;
}
数据数量size_t QueueSize(Queue* q)
{
size_t num = 0;
QueueNode*ptr = q->_head->_next;
while (ptr)
{
ptr=ptr->_next;
num++;
}
return num;
}
队列判空int QueueEmpty(Queue* q)
{
if (q->_head->_next = NULL)
return 0;
else
return 1;
}