1.主要实现了创建,入队,出队,销毁等操作,代码如下:
//
// Queue.h
// Queue
//
// Created by Mac on 15/11/22.
// Copyright © 2015年 Mac. All rights reserved.
//
#ifndef Queue_h
#define Queue_h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct _tagQueue{
int capacity;
int size;
int front;
int rear;
void** data;
}Queue;
//queue create
Queue* QueueCreate(int maxSize);
//enqueue
int EnQueue(Queue* q,void* data);
//dequeue
void* DeQueue(Queue* q);
//isempty
bool QueueIsEmpty(Queue* q);
//isfull
bool QueueIsFull(Queue* q);
//queue destroy
void QueueDestroy(Queue* q);
#endif /* Queue_h */
//
// Queue.c
// Queue
//
// Created by Mac on 15/11/22.
// Copyright © 2015年 Mac. All rights reserved.
//
#include "Queue.h"
Queue* QueueCreate(int maxSize){
Queue* q = (Queue*)malloc(sizeof(Queue));
if (q == NULL) {
return NULL;
}
memset(q, 0, sizeof(Queue));
q->data = (void**)malloc(sizeof(void*)*maxSize);
if(q->data == NULL){
return NULL;
}
memset(q->data, 0, sizeof(void*)*maxSize);
q->capacity = maxSize;
return q;
}
//enqueue
int EnQueue(Queue* q,void* data){
if (q == NULL || data == NULL) {
return -1;
}
if (QueueIsFull(q)) {
return -2;
}
if (q->front == q->rear == 0) {
q->front = 1;
}
q->rear = (q->rear + 1)%q->capacity;
q->data[q->rear] = data;
q->size++;
return 0;
}
//dequeue
void* DeQueue(Queue* q){
if (q == NULL) {
return NULL;
}
if (QueueIsEmpty(q)) {
return NULL;
}
void* data = q->data[q->front];
q->data[q->front] = NULL;
q->front = (q->front+1)%q->capacity;
q->size--;
return data;
}
//isempty
bool QueueIsEmpty(Queue* q){
return q->size == 0;
}
//isfull
bool QueueIsFull(Queue* q){
return q->size == q->capacity;
}
//queue destroy
void QueueDestroy(Queue* q){
if (q == NULL) {
return;
}
for (int i = 0; i < q->size; i++) {
if(q->data[i] != NULL){
free(q->data[i]);
q->data[i] = NULL;
}
}
free(q->data);
q->data = NULL;
free(q);
q = NULL;
}