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