队列

    头文件:

#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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值