数据结构 循环队列

头文件

cpp 复制代码
#pragma once
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
using namespace std;
#define max_size 10
typedef struct circlequeue {
	int* data;
	int front;//队头指针
	int rear;//队尾指针
}circlequeue, * pcirclequeue;

//初始化
void init_queue(circlequeue* p);
//入队
bool push(circlequeue* p, int val);
//出队
bool pop(circlequeue* p);
//获取队头元素值
int front(circlequeue* p);
//查找
int search(circlequeue* p, int val);
//判空
bool is_empty(circlequeue* p);
//判满 
bool is_full(circlequeue* p);
//清空
void clear(circlequeue* p);
//销毁
void destroy(circlequeue* p);
//打印
void show(circlequeue* p);
//有效值个数
int getsize(circlequeue* p);

源文件

cpp 复制代码
#include"循环队列.h"

//初始化
void init_queue(circlequeue* p) {
    assert(p != nullptr);
    p->data = (int*)malloc(sizeof(int) * max_size);
    if (p->data == nullptr) {
        printf("内存分配失败\n");
        return;
    }
    p->front = 0;
    p->rear = 0;
}
//判空
bool is_empty(circlequeue* p) {
    assert(p != nullptr);
    return p->front == p->rear;
}
//入队
bool push(circlequeue* p, int val) {
    assert(p != nullptr);
    if (is_full(p))return false;
    p->data[p->rear] = val;
    p->rear = (p->rear + 1) % max_size;
    return true;
}
//出队
bool pop(circlequeue* p) {
    assert(p != nullptr);
    if (is_empty(p))return false;
    p->front = (p->front + 1) % max_size;
    return true;
}
//获取队头元素值
int front(circlequeue* p) {
    assert(p != nullptr);
    if (is_empty(p))return NULL;
    return p->data[p->front];
}
//查找
int search(circlequeue* p, int val) {
    assert(p != nullptr);
    if (is_empty(p))return -1;
    int i = p->front;
    int pos = 0;
    while (i != p->rear) {
        if (p->data[i] == val) return pos;
        i = (i + 1) % max_size;
        pos++;
    }
    return -1;
}

//判满 
bool is_full(circlequeue* p) {
    assert(p != nullptr);
    return ((p->rear + 1) % max_size == p->front);
}
//清空
void clear(circlequeue* p) {
    assert(p != nullptr);
    p->front = 0;
    p->rear = 0;
}
//销毁
void destroy(circlequeue* p) {
    assert(p != nullptr);
    free(p->data);
    p->data = nullptr;
    p->front = 0;
    p->rear = 0;
}
//打印
void show(circlequeue* p) {
    assert(p != nullptr);
    if (is_empty(p)) return;
    printf("队列元素: ");
    int i = p->front;
    while (i != p->rear) {
        printf("%d ", p->data[i]);
        i = (i + 1) % max_size;
    } printf("\n");
}
//有效值个数
int getsize(circlequeue* p) {
    assert(p != nullptr);
    return (p->rear - p->front + max_size) % max_size;
}
相关推荐
50万马克的面包2 分钟前
数据结构01-数据结构概念与复杂度-博客稿
数据结构
Logic10125 分钟前
C语言/数据结构贪心算法题解:字符串趋同——逐位统计最高频率求最小修改代价
c语言·数据结构·贪心算法·字符串·时间复杂度·频率统计·算法题
红豆诗人2 小时前
C++二叉搜索树:查找、插入和删除为什么这样写
数据结构·c++·算法
H.莓飛2 小时前
【数据结构】堆_OJ题
linux·数据结构·算法
7yewh11 小时前
SLAM 三维空间刚体运动(2)
数据结构·人工智能·机器人·嵌入式·slam
leikooo12 小时前
用餐厅和盘子理解栈和堆
java·数据结构·链表·rust
lvwangshu15 小时前
登录日志 题解
数据结构·线段树·题解·技巧·性质题·思维好题·细节题
CQU_JIAKE15 小时前
10.2【A】
数据结构
C++ 老炮儿的技术栈16 小时前
不一样的数值交换
数据结构·c++·人工智能·算法·c·csdn开发云
青山木17 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划