数据结构---链式队列

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

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

操作:

(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;
}

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

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

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

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

相关推荐
土司大王3 小时前
LeetCode hot100——除了自身以外数组的乘积
数据结构·算法·leetcode
神威难绷泪7 小时前
数据结构:哈希表 算法相关 排序算法
数据结构
Zguigo9 小时前
树的前序|中序|后序遍历【使用栈实现】
数据结构·算法
2401_869769599 小时前
list 2
数据结构·list
ambition2024212 小时前
操作系统同步:读者-写者问题与读写公平法详解(附每个 PV 操作含义)
linux·开发语言·数据结构·unix
疯狂打码的少年1 天前
【数据结构】图的存储结构:邻接矩阵与邻接表
数据结构·笔记
203号居民1 天前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
2401_862880821 天前
数据结构 --- 栈
c语言·数据结构·算法
额额额对了1 天前
数据结构:二叉树
c语言·数据结构·算法
qeen871 天前
【数据结构】红黑树的算法原理解析与实现
开发语言·数据结构·c++·算法·红黑树