第三章 栈和队列

链式队列的简单案例实现:

#include <stdio.h>
#include <iostream>

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1

typedef int Status;
typedef int QElemType;
//队列的链式存储结构
typedef struct QNode
{
    QElemType data;
    struct QNode *next;
} QNode, *QueuePtr;
typedef struct
{
    QueuePtr front;
    QueuePtr rear;
} LinkQueue;

//初始化
//构造一个空队列,头指针和尾指针都指向头结点
Status InitQueue(LinkQueue &Q)
{
    Q.front = Q.rear = new QNode;
    Q.front->next = NULL;
    return OK;
}

//入队
Status EnQueue(LinkQueue &Q, QElemType e)
{
    QNode *p = new QNode;
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    return OK;
}

//出队
Status DeQueue(LinkQueue &Q, QElemType &e)
{
    if (Q.front == Q.rear)
    {
        puts("出队失败..");
        return ERROR;
    }
    QNode *p = Q.front->next; // 指向首元结点 方便操作和后续释放
    e = p->data;
    Q.front->next = p->next;
    if (Q.rear == p->next)
        Q.front = Q.rear; // 将最后一个结点出栈,则为设置为空
    delete p;
    return OK;
}

//取队头元素
QElemType GetHead(LinkQueue Q)
{
    if (Q.front == Q.rear)
    {
        puts("取队头元素失败...");
        return ERROR;
    }
    return Q.front->next->data;
}

int main(void)
{

    LinkQueue Q;
    puts("初始化链队...");
    InitQueue(Q);
    puts("将data为1 2 3的结点入队...");
    EnQueue(Q, 1);
    EnQueue(Q, 2);
    EnQueue(Q, 3);
    puts("入队成功..");
    puts("取队头元素...");
    printf("e: %d\n", GetHead(Q));
    puts("出队ing...");
    int e;
    DeQueue(Q, e);
    printf("出队的元素e: %d\n", e);
    puts("取队头元素...");
    printf("e: %d\n", GetHead(Q));
    delete Q.front;

    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值