DS:顺序队列

//SeqQueue.h

#ifndef _SQQUEUE_H
#define _SQQUEUE_H

#define MAXSIZE 50
typedef struct Queue* SeqQueue;
struct Queue{
    int data[MAXSIZE];  // 数据
    int front;   // 队头
    int rear;    // 队尾
};

SeqQueue Create();
int getLength(SeqQueue Sq);
int IsEmpty(SeqQueue Sq);
void Insert(SeqQueue Sq, int val);
int Del(SeqQueue Sq);
int GetHead(SeqQueue Sq);
void Clear(SeqQueue Sq);
void Destory(SeqQueue Sq);

#endif

//SeqQueue.c

#include "SeqQueue.h"
#include <string.h>
#include <stdio.h>
#include<stdlib.h>

SeqQueue Create()
{
    SeqQueue Sq = (SeqQueue)malloc(sizeof(struct Queue));
    Sq->front = Sq->rear = -1;
    memset(Sq->data, 0, MAXSIZE * sizeof(int));
    return Sq;
}

int getLength(SeqQueue Sq)
{
    return Sq->rear - Sq->front; // 队头队尾之差
}

int IsEmpty(SeqQueue Sq)
{
    if(Sq->rear == Sq->front)
    {
        return 1;
    }
    return 0;
}

void Insert(SeqQueue Sq, int val)
{
    // 数组前面是队头,后边是队尾
    if(Sq->rear == MAXSIZE-1){
        printf("队列已满,无法再插入元素!\n");
    }
    // 空队列
    if (IsEmpty(Sq)){
        Sq->front = Sq->rear = 0;
        Sq->data[Sq->rear] = val;
        Sq->rear++;
    }
    else
    {
        Sq->data[Sq->rear] = val;
        Sq->rear++;
    }
}

int Del(SeqQueue Sq)
{
    if(IsEmpty(Sq))
    {
        printf("队列为空,无元素可弹!\n");
        return 10000;  // 返回错误标识
    }
    int temp = Sq->data[Sq->front];
    Sq->front++; //取到队头元素后,front向后移动
    return temp;
}

int GetHead(SeqQueue Sq)
{
    if(IsEmpty(Sq))
    {
        printf("队列为空,无元素可弹!\n");
        return 10000;  // 返回错误标识
    }
    return Sq->data[Sq->front];
}

void Clear(SeqQueue Sq)
{
    Sq->front = Sq->rear = -1;
    printf("队列已清空!\n");
}

void Destory(SeqQueue Sq)
{
    free(Sq);
    printf("队列已销毁!\n");
}

//main.c

#include "SeqQueue.h"
#include <stdio.h>
#include<stdlib.h>

int main()
{
    SeqQueue Sq = Create();
    srand((unsigned)time(0));
    for (size_t i = 0; i < 10; i++)
    {
        Insert(Sq,rand()%100);
    }
    printf("队列长度:%d\n", getLength(Sq));
    printf("队头元素 出队元素\n");
    while (Sq->front != Sq->rear)  // 出队列,循环队列不能为空
    {
        int ret = GetHead(Sq);
        printf("%d     ",ret);
        ret = Del(Sq);//出队列
        printf("%d\n",ret);
    }
    printf("队列长度:%d\n", getLength(Sq));
    Clear(Sq);
    Destory(Sq);
    
    system("pause");
    return 0;
}
posted @ 2021-06-24 00:16  im天行  阅读(68)  评论(0编辑  收藏  举报