数据结构-队列

队列

先插入的将被先删除,先入先出表

顺序存储

#include 
# include "stdio.h"
# include "stdlib.h"


typedef int Position;

typedef struct QNode *PtrToQNode;
typedef int ElementType ;
typedef  PtrToQNode Queue;

struct QNode{
    ElementType * Data;
    Position Front, Rear;
    int MaxSize;
};

// 创建循环队列
Queue CreateQueue(int MaxSize){
    Queue Q = (Queue) malloc(sizeof (struct QNode));
    Q->Data = (ElementType *) malloc(sizeof (ElementType)*MaxSize);
    Q->Front = 0;
    Q->Rear = 0;
    Q->MaxSize = MaxSize;
    return Q;
}

// 判断队列是否已满
bool IsFull(Queue Q){
    return ((Q->Rear+1)%Q->MaxSize == Q->Front);
}

// 插入元素
bool AddQ(Queue Q, ElementType X){
    if (IsFull(Q)){
        printf("队列已满,无法插入\n");
        return false;
    } else{
        Q->Rear = (Q->Rear + 1)%Q->MaxSize;
        Q->Data[Q->Rear] = X;
        return true;
    }
}

// 判断队列是否已空
bool IsEmpty(Queue Q){
    return (Q->Front == Q->Rear);
}

// 删除元素
ElementType DeleteQ(Queue Q){
    if(IsEmpty(Q)){
        printf("队列已满,无法删除\n");
        return false;
    } else{
        Q->Front = (Q->Front + 1)%Q->MaxSize;
        return Q->Data[Q->Front];
    }
}

void PrintData(Queue Q){
    for (int i = Q->Front+1; i<= Q->Rear ; i++)
        printf("%d\t",Q->Data[i]);
    printf("\n");
}

int main(){
    Queue q;
    q = CreateQueue(3);
    AddQ(q,3);
    PrintData(q);
    AddQ(q,4);
    PrintData(q);
    DeleteQ(q);
    PrintData(q);
}

你可能感兴趣的:(C语言-数据结构,数据结构,c++,算法)