一、什么是队列?
- 队列是一种先进先出FIFO的一种线性结构,也有链式和顺序之分。
- 入队的一端称为队尾,出队的一端称为对头。
1.链式队列的设计
typedef struct Node
{
int data;//数据域,没存放节点的值
struct Node* next;//指针域,存放下一个节点的地址
}Node, * PNode;
//重新设计的头结点
typedef struct LQueue
{
struct Node* prior;//指向头结点;
struct Node* tail;//指向尾结点;
}Lqueue, * PLQueue;
2.链式队列的基本操作
(1)初始化
void InitLQueue(PLQueue plq)
{
assert(plq != nullptr);
if (plq == nullptr)return ;
plq->prior = nullptr;
plq->tail = nullptr;
}
(2)入队(表尾入队)
入队有两种情况:
- 头结点为空:指向数据结点的头尾指针都要改变。
- 头结点不为空:指向数据结点的头指针改变,尾指针不改变。
bool Push(PLQueue plq, int val)
{
assert(plq != nullptr);
if (plq == nullptr)return false;
Node* pnewnode = (Node*)malloc(sizeof(Node));//申请新结点,并对其数据域和指针域初始化;
if (pnewnode == nullptr)return;
pnewnode->data = val;
pnewnode->next = nullptr;
if (plq->prior == nullptr)//第一种情况;
{
plq->prior = pnewnode;
plq->tail = pnewnode;
}
else //第二种情况;
{
pnewnode->next = plq->tail->next;
plq->tail->next = pnewnode;
plq->tail = pnewnode;
}
return true;
}
(2)判空
bool IsEmpty(PLQueue plq)
{
assert(plq != NULL);
if(NULL == plq) return false;