数据结构---链式队列

基于链式存储结构实现的队列

实现方式:带头结点的单链表

操作:

(1)初始化

复制代码
#include<stdio.h>
#include<stdlib.h>
//链式队列
//链表的结点结构
typedef struct Node
{
    int data;
    struct Node* next;
}QNode;
//声明队列结构(用结构体声明队列结构的好处是可以声明多个队列)
typedef struct queue
{
    QNode* head;
    QNode* tail;
}Queue;
//初始化
Queue* InitQueue()
{
    Queue *q = (Queue*)malloc(sizeof(Queue));
    if(q == NULL)
    {
        printf("内存申请失败\n");
        return NULL;
    }
    QNode *p = (QNode*)malloc(sizeof(QNode));
    if(p == NULL)
    {
        printf("内存申请失败\n");
        return NULL;
    }
    p->next = NULL;
    q->head = p;
    q->tail = p;
    return q;
}

(2)入队(使用带尾指针的尾插法)

复制代码
//入队(尾插法)
Queue* push(Queue *q,int k)
{
    QNode* p = (QNode*)malloc(sizeof(QNode));
    if(p == NULL)
    {
        printf("内存申请失败\n");
        return q;
    }
    p->data = k;
    p->next = q->tail->next;
    q->tail->next = p;
    q->tail = p;
    return q;
}

(3)出队

复制代码
//出队
Queue* pop(Queue* q)
{
    if(q->head->next == NULL)
    {
        printf("空队列\n");
        return q;
    }
    QNode* temp = q->head->next;
    q->head->next = q->head->next->next;
    if(temp == q->tail)//防止尾指针称为野指针
    {
        q->tail = q->head;
    }
    free(temp);
    temp = NULL;
    return q;
}

(4)判空

复制代码
//判空
int isEmpty(Queue* q)
{
    if(q->head == q->tail)
    {
        return 1;   
    }
    return 0;
}

链式队列没有判满操作,是无限的

相比较于顺序队列,后面没有循环链式队列,

因为链式队列不存在假溢出的情况

除了链式队列和顺序队列还有优先队列和双端队列

相关推荐
码农小韩33 分钟前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习
想做后端的小C1 小时前
408 数据结构:数据结构三要素——逻辑结构、物理(存储)结构和运算操作
数据结构
栈与堆1 小时前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
嵌入式进阶行者2 小时前
【算法】TLV格式解析实例:华为OD机考双机位A卷 - TLV解析 Ⅱ
数据结构·c++·算法
星火开发设计2 小时前
C++ map 全面解析与实战指南
java·数据结构·c++·学习·算法·map·知识
仰泳的熊猫2 小时前
题目1099:校门外的树
数据结构·c++·算法·蓝桥杯
Z1Jxxx2 小时前
反序数反序数
数据结构·c++·算法
vyuvyucd3 小时前
C++排序算法全解析
java·数据结构·算法
ohoy3 小时前
RedisTemplate 使用之List
数据结构·windows·list
星马梦缘4 小时前
算法与数据结构
数据结构·c++·算法·动态规划·克鲁斯卡尔·kahn