当前位置:网站首页>C语言队列
C语言队列
2022-07-07 04:33:00 【pythoncjavac++】
目录
队列有关概念
首先队列最大的特点是“先进先出”,只能在一端插入,另一端删除,插入的一端是队尾,删除的一端是队头。
队列的创建
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}QNode;
typedef struct Queue
{
QNode* head;
QNode* tail;
}Queue;
这里要创建两个结构体,因为这里要记录一下他的头和尾,这样可以方便进行插入和删除。
队列的初始化
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
队列的插入
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
if (pq->tail == NULL)
{
pq->tail = pq->head = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
}
队列的删除
void QueuePoq(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QNode* cur = pq->head->next;
free(pq->head);
pq->head = cur;
}
}
取队列的头
QDataType QueueFront(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
取队列的尾
QDataType QueueBack(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
队列元素的数量
int QueueSize(Queue* pq)
{
assert(pq);
int size = 0;
QNode* cur = pq->head;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}
判断队列是否为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
销毁队列
void QueueDestory(Queue* pq)
{
assert(pq);
QNode* cur = pq->head;
while (cur)
{
QNode* aq = cur->next;
free(cur);
cur = aq;
}
pq->head = pq->tail = NULL;
}
边栏推荐
猜你喜欢
[UTCTF2020]file header
Operation suggestions for today's spot Silver
Visualization Document Feb 12 16:42
Few-Shot Learning && Meta Learning:小样本学习原理和Siamese网络结构(一)
2022-07-06: will the following go language codes be panic? A: Meeting; B: No. package main import “C“ func main() { var ch chan struct
Why should we understand the trend of spot gold?
自定义类加载器加载网络Class
2022制冷与空调设备运行操作复训题库及答案
今日现货白银操作建议
Linux server development, SQL statements, indexes, views, stored procedures, triggers
随机推荐
[UVM practice] Chapter 1: configuring the UVM environment (taking VCs as an example), run through the examples in the book
misc ez_ usb
Numbers that appear only once
【斯坦福计网CS144项目】Lab4: TCPConnection
242. Bipartite graph determination
Button wizard script learning - about tmall grabbing red envelopes
自定义类加载器加载网络Class
【VHDL 并行语句执行】
buuctf misc USB
leanote私有云笔记搭建
CTF daily question day43 rsa5
resource 创建包方式
pytest+allure+jenkins安装问题:pytest: error: unrecognized arguments: --alluredir
nacos
Wx is used in wechat applet Showtoast() for interface interaction
nacos
What is the difference between TCP and UDP?
今日现货白银操作建议
Pytest+allure+jenkins environment -- completion of pit filling
Qt学习28 主窗口中的工具栏