c语言实现队列

用数组或者链表实现队列,先进先出

queue.h

//
// Created by gxf on 2020/3/8.
//

#ifndef UNTITLED_QUEUE_H
#define UNTITLED_QUEUE_H

void initQueue();
void enqueue(int data);
int dequeue();
int isFull();
int isEmpty();
void destroy();
void printQueue();

#endif //UNTITLED_QUEUE_H

queue.c

//
// Created by gxf on 2020/3/8.
//
#include "queue.h"
#include <stdio.h>
#include <stdlib.h>

int front = 0;
int rear = 0;
int *queue = NULL;
int length = 100;
int size = 0;


void initQueue() {
    queue = malloc(sizeof(int) * length);
}

void enqueue(int data) {
    if (!isFull()) {
        queue[rear] = data;
        rear = (rear + 1) %length;
        size ++;
    }
    else
        printf("queue is full\n");
}

int dequeue() {
    if (!isEmpty()) {
        int res = queue[front];
        front = (front + 1) % length;
        size --;
        return res;
    }
    printf("queue is empty\n");
}

int isFull() {
    if (size == length)
        return 1;
    return 0;
}

int isEmpty() {
    if (size == 0)
        return 1;
    return 0;
}

void destroy(){
    if (queue)
        free(queue);
}

void printQueue() {
    while (!isEmpty()) {
        printf("%d ", dequeue());
    }
    printf("\n");
}

main.c

//
// Created by gxf on 2020/3/8.
//

#include "queue.h"

int main() {
    int a[5] = {4, 9, 2, 3, 1};
    initQueue();
    for (int i =0; i < sizeof(a) / sizeof(int); i++) {
        enqueue(a[i]);
    }
    printQueue();
    destroy();
    
    
    return 0;
}

  

posted on 2020-03-08 19:41  luckygxf  阅读(888)  评论(0编辑  收藏  举报

导航