队列及其基本操作

链式队列头文件

#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#define _CRT_SECURE_NO_WARNINGS 1
typedef int QDataType;
typedef struct LinkList
{
    struct LinkLis *next;
    QDataType data;
}QLinkList;

typedef struct Queue
{
    QLinkList *front;
    QLinkList *rear;
    int sz;
}Queue;

void QueueInit(Queue* Qlist);
void QueuePush(Queue* Qlist, QDataType data);
void QueuePop(Queue* Qlist);
QDataType QueueFront(Queue* Qlist);
QDataType QueueBack(Queue*  Qlist);
int QueueSize(Queue* Qlist);
int QueueEmpty(Queue* Qlist);

链式队列操作

#include "Queue.h"
QLinkList* BuyNode( QDataType Data)
{
    QLinkList *cur = (QLinkList*)malloc(sizeof(QLinkList));
    if (cur == NULL)
    {
        printf("QueueInit :: malloc failed\n");
        exit(0);
    }
    cur->data = Data;
    cur->next = NULL;
    return cur;
}
void QueueInit(Queue* Qlist)
{
    Qlist->front = NULL;
    Qlist->rear = NULL;
    Qlist->sz = 0;
}
void QueuePush(Queue*Qlist, QDataType data)
{
    assert(Qlist);
    QLinkList *cur = BuyNode(data);
    QLinkList *pcur = Qlist->front;
    if (pcur != NULL)
    {
        while (pcur->next != NULL)
        {
            pcur = pcur->next;
        }
        pcur->next = cur;
        Qlist->rear = pcur->next;
    }
    else
    {
        Qlist->front = cur;
        Qlist->rear = cur;
    }
    Qlist->sz++;
}
void QueuePop(Queue* Qlist)
{
    assert(Qlist);
    if (Qlist->sz == 0)
    {
        printf("队列为空,无法出队!\n");
        system("pause");
        return;
    }
    QLinkList *cur = Qlist->front;
    Qlist->front = Qlist->front->next;
    free(cur);
    Qlist->sz--;
}
QDataType QueueFront(Queue* Qlist)
{
    assert(Qlist);
    if (Qlist->sz == 0)
    {
        printf("队列为空,无法获取队首元素 \n");
        return 0;
    }
    return Qlist->front->data;
}
QDataType QueueBack(Queue*  Qlist)
{
    assert(Qlist);
    if (Qlist->sz == 0)
    {
        printf("队列为空,无法获取队尾元素 \n");
    }
    return Qlist->rear->data;
}
int QueueSize(Queue* Qlist)
{
    assert(Qlist);
    return Qlist->sz;
}
int QueueEmpty(Queue* Qlist)
{
    assert(Qlist);
    if (Qlist->sz = 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

验证

#include "Queue.h"
int main()
{
    Queue q;
    QueueInit(&q);
    QueuePush(&q, 1);
    QueuePush(&q, 2);
    QueuePush(&q, 3);
    QueuePush(&q, 4);
    QueuePush(&q, 5);
    QueuePop(&q);
    printf("QFront = %d \n",QueueFront(&q));
    printf("QRear = %d \n", QueueBack(&q));
    printf("QSize = %d \n", QueueSize(&q));
    printf("Queue is Empty ? == %d \n", QueueEmpty(&q));
    system("pause");

    return 0;
}

猜你喜欢

转载自blog.csdn.net/H_Strong/article/details/82225349
今日推荐