mid-term exam-T4

队列-链队基本操作

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef int datatype;

typedef struct node
{
    datatype data;
    struct node *next;
} QNode;

typedef struct
{
    QNode *front, *rear;
} LQueue;


LQueue *Init_LQueue()
{
    //初始化带头节点的空链队
    LQueue *q = (LQueue *)malloc(sizeof(LQueue));
    q->front = q->rear = NULL;
    return q;
}

void In_LQueue(LQueue *lq, datatype x)
{
    //入队
    QNode *p = (QNode *)malloc(sizeof(QNode));
    p->data = x;
    p->next = NULL;
    if (lq->rear == NULL) //若链队为空,则新结点既是首结点又是尾结点
    {
        lq->front = lq->rear = p;
    }
    else
    {                       //若链队不空
        lq->rear->next = p; //q的尾指针的后继是插入的p
        lq->rear = p;       //q的尾指针指向p
    }
}

int Empty_LQueue(LQueue *lq)
{
    //判断空队,如果空,返回1;非空,返回0;
    if (lq->rear == NULL)
    {
        return (1);
    }
    else
    {
        return (0);
    }

    return 0;
}

int Out_LQueue(LQueue *lq, datatype *x)
{
    if (Empty_LQueue(lq))
    {
        printf("empty\n");
        return 0;
    }
    else
    {
        //出队
        QNode *t;
        t = lq->front; //t指向首结点
        if (lq->front == lq->rear)
        {
            lq->front = lq->rear = NULL;
        }
        else
        {
            lq->front = lq->front->next;
        }
        *x = t->data;
        free(t);
        return 0;
    }
}

int main()
{
    LQueue *q = Init_LQueue();
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);

    In_LQueue(q, a);
    Out_LQueue(q, &a);

    In_LQueue(q, b);
    In_LQueue(q, c);

    Out_LQueue(q, &c);
    Out_LQueue(q, &b);
    Out_LQueue(q, &a);

    printf("%d %d %d", a, b, c);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值