C语言实现队列的示例详解

  #include

  #include

  #include

  #include

  typedef int QDateType;

  typedef struct QueueNode

  {

  QDateType val;

  struct QueueNode* next;

  }QueueNode;

  typedef struct Queue

  {

  QueueNode* head;

  QueueNode* tail;

  }Queue;

  void QueueInti(Queue* pq)

  {

  assert(pq);

  pq->head = pq->tail = NULL;

  }

  void QueueDestory(Queue* pq)

  {

  assert(pq);

  QueueNode* cur = pq->head;

  while (cur)

  {

  QueueNode* next = cur->next;

  free(cur);

  cur = next;

  }

  pq->tail = pq->head = NULL;

  }

  void QueuePush(Queue* pq, QDateType x)

  {

  assert(pq);

  QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));

  if (NULL == newNode)

  {

  printf("malloc error

  ");

  exit(-1);

  }

  newNode->val = x;

  newNode->next = NULL;

  if (pq->tail == NULL)

  {

  assert(pq->head == NULL);

  pq->head = pq->tail = newNode;

  }

  else

  {

  pq->tail->next = newNode;

  pq->tail = newNode;

  }

  }

  void QueuePop(Queue* pq)

  {

  assert(pq);

  assert(pq->head && pq->tail);

  if (pq->head->next == NULL)

  {

  free(pq->head);

  pq->head = pq->tail = NULL;

  }

  else

  {

  QueueNode* next = pq->head->next;

  free(pq->head);

  pq->head = next;

  }

  }

  bool QueueEmpty(Queue* pq)

  {

  assert(pq);

  return pq->head == NULL;

  }

  QDateType QueueFront(Queue* pq)

  {

  assert(pq);

  assert(pq->head);

  return pq->head->val;

  }

  int QueueSize(Queue* pq)

  {

  assert(pq);

  QueueNode* cur = pq->head;

  int count = 0;

  while (cur)

  {

  cur = cur->next;

  count++;

  }

  return count;

  }