目錄
- 前言
- 1. 佇列的概念及結構
- 2. 佇列的實作
- 2.1 queue.h
- 2.2 queue.c
- 2.3 test.c
- 后記
前言
hello,大家好,這期文章我們來分享資料結構關于佇列的知識,希望對大家有所幫助,閑言少敘,現在開始,
1. 佇列的概念及結構
佇列:只允許在一端進行插入資料操作,在另一端進行洗掉資料操作的特殊線性表,佇列具有先進先出FIFO(First In First Out) 入佇列:進行插入操作的一端稱為隊尾 出佇列:進行洗掉操作的一端稱為隊頭


2. 佇列的實作
2.1 queue.h
#include<stdio.h>
#include<stdbool.h>
#include<assert.h>
#include<malloc.h>
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode*next;
QDataType data;
}QueueNode;
typedef struct Queue
{
QueueNode *head;
QueueNode *tail;
}Queue;
void QueueInit(Queue *pq);
void QueueDestory(Queue *pq);
void QueuePush(Queue *pq,QDataType x);
void QueuePop(Queue *pq);
QDataType QueueFront(Queue *pq);
QDataType QueueBack(Queue *pq);
bool QueueEmpty(Queue *pq);
int QueueSize(Queue *pq);
2.2 queue.c
#include"queue.h"
void QueueInit(Queue *pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
void QueueDestory(Queue *pq)
{
assert(pq);
QueueNode *cur = pq->head;
while (cur)
{
QueueNode *next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
void QueuePush(Queue *pq, QDataType x)
{
assert(pq);
QueueNode *newnode = (QueueNode*)malloc(sizeof(QueueNode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
if (pq->tail == NULL)
{
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;
}
}
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;
}
bool QueueEmpty(Queue *pq)
{
assert(pq);
return pq->head == NULL;
}
int QueueSize(Queue *pq)
{
int size = 0;
QueueNode *cur = pq->head;
while (cur)
{
QueueNode *next = cur->next;
++size;
cur = cur->next;
}
return size;
}
2.3 test.c
#include"queue.h"
void TestOne()
{
Queue q;
QueueInit(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 4);
while (!QueueEmpty(&q))
{
printf("%d ", QueueFront(&q));
QueuePop(&q);
}
printf("\n");
QueueDestory(&q);
}
int main()
{
TestOne();
return 0;
}
后記
好的,我們這期文章就分享到這里了,下期見,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/300743.html
標籤:其他
上一篇:十分鐘弄懂最快的APP自動化工具uiautomator2
下一篇:Linux中行程的六種狀態
