队列操作的实现-链式存储

本文深入探讨了如何使用链式存储结构实现队列操作。从队列的基本概念出发,详细阐述了入队、出队的过程,并通过实例解析了链表节点的添加和删除。同时,讨论了链式队列相较于数组队列的优势,如动态扩容、空间利用率高等特点。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;

//链式队列结点
typedef struct Node{
     int data;
     struct Node *next;
}Node;

//队列
typedef struct {
    Node *front,*rear;
}LinkQueue;

//初始化
void init(LinkQueue *q){
    q->front=(Node*)malloc(sizeof(Node));
    if(q->front!=NULL){
        q->rear=q->front;
        q->front->next=NULL;
    }
}
//判空
bool isempty(LinkQueue *q){
    if(q->front==q->rear)
        return true;
    else
        return false;
}
//入队
void enqueue(LinkQueue *q,int e){
    //创建新结点,插入到链尾
    Node *s=(Node *)malloc(sizeof(Node));
    s->data=e;
    s->next=NULL;
    printf("%d 入队成功.\n",e);
    q->rear->next=s;
    q->rear=s;//修改队尾指针
}
//出队
void dequeque(LinkQueue *q){
    if(q->front==q->rear)
        printf("empty");
    int x;
    Node *s=q->front->next;
    x = s->data;
    printf("%d 出队.\n",x);
    q->front->next=s->next;
    if(q->rear==s)
        q->rear=q->front;//若原队列中只有一个节点,删除后为空
    s=NULL;
}
//取队头元素
int gettop(LinkQueue *q){
    int x;
    if(q->front==q->rear)
        return 0;
    else
        x=q->front->next->data;
    return x;
}
//输出
void show(LinkQueue *q){
    while(!isempty(q)){
        cout<<q->front->next->data<<" ";
        q->front->next=q->front->next->next;
    }
    cout<<endl;
}
int main()
{
    LinkQueue q;
    LinkQueue *s;
    s=&q;
    //初始化队列
    init(s);
    //入队
    for(int i=0;i<5;i++)
        enqueue(s,i);
    //出队
    dequeque(s);
    //取队头元素
    int x = gettop(s);
    cout<<"队头元素是:"<<x<<endl;
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值