头文件:
#ifndef __MYQUEUE_H__
#define __MYQUEUE_H__
#define ret_val_if_fail(p, val)\
if (!(p)){printf("%s:%d error: "#p" failed.\n", __func__, __LINE__); return val;}
#define ret_if_fail(p)\
if (!(p)){printf("%s:%d error: "#p" failed.\n", __func__, __LINE__); return;}
struct _MyQueue;
typedef struct _MyQueue MyQueue, *MyQueuePtr;
MyQueuePtr myqueue_create();
void myqueue_destory(MyQueuePtr thiz);
int myqueue_empty(MyQueuePtr thiz);
void* myqueue_front(MyQueuePtr thiz);
void myqueue_pop(MyQueuePtr thiz);
void myqueue_push(MyQueuePtr thiz, void* obj);
#endif
实现源文件:
#include <stdio.h>
#include <stdlib.h>
#include "myqueue.h"
typedef struct _QueueNode
{
void* data;
struct _QueueNode* next;
}QueueNode, *QueueNodePtr;
struct _MyQueue
{
QueueNodePtr front;
QueueNodePtr back;
};
MyQueuePtr myqueue_create()
{
MyQueuePtr retPtr = (MyQueuePtr)malloc(sizeof(MyQueue));
retPtr->front = (QueueNodePtr)malloc(sizeof(QueueNode));
memset(retPtr->front, 0, sizeof(QueueNode));
retPtr->back = retPtr->front;
}
void myqueue_destroy(MyQueuePtr thiz)
{
ret_if_fail(thiz != NULL);
ret_if_fail(thiz->front != NULL);
QueueNodePtr* p = thiz->front;
QueueNodePtr* q = NULL;
while (p != NULL)
{
q = p;
p = p->next;
free(q->data);
free(q);
}
free(thiz);
}
int myqueue_empty(MyQueuePtr thiz)
{
ret_val_if_fail(thiz != NULL, 1);// if the queue is not created, then we say it's empty
if (thiz->front == thiz->back)
return 1;
return 0;
}
void* myqueue_front(MyQueuePtr thiz)
{
ret_val_if_fail(thiz != NULL, NULL);
ret_val_if_fail(thiz->front != NULL, NULL);
ret_val_if_fail(thiz->front->next != NULL, NULL);
return thiz->front->next->data;
}
void myqueue_pop(MyQueuePtr thiz)
{
ret_if_fail(thiz != NULL);
ret_if_fail(thiz->front != NULL);
ret_if_fail(thiz->front->next != NULL);
QueueNodePtr frontNode = thiz->front->next;
if (frontNode->next == NULL)
thiz->back = thiz->front;
thiz->front->next = frontNode->next;
free(frontNode->data);
free(frontNode);
}
void myqueue_push(MyQueuePtr thiz, void* obj)
{
ret_if_fail(thiz != NULL);
ret_if_fail(thiz->back != NULL);
QueueNodePtr newPtr = (QueueNodePtr)malloc(sizeof(QueueNode));
newPtr->next = NULL;
newPtr->data = obj;
thiz->back->next = newPtr;
thiz->back = newPtr;
}