Queue dynamic chain storage implementation code sharing

  • 2020-04-02 02:12:25
  • OfStack


#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <assert.h>
#include "DynaLnkQueue.h"

bool InitQueue(LinkQueue *Q)
{
 Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode));
 if(!Q->front)
  return false;
 Q->front->next = NULL;
 return true;
}

void DestroyQueue(LinkQueue *Q)
{
 while(Q->front)
 {
  Q->rear = Q->front->next;
  free(Q->front);
  Q->front = Q->rear;
 }
}

bool QueueEmpty(LinkQueue Q)
{
 if(Q.front == Q.rear)
  return true;
 return false;
}

int QueueLength(LinkQueue Q)
{
 ElemType count=0;
 QueuePtr p = Q.front->next;
 while(p->next != NULL)
 {
  ++count;
  p = p->next;
 }
 return count;
}

bool GetHead(LinkQueue Q, ElemType *e)
{
 if(QueueEmpty(Q) == false)
 {
  e = &Q.front->next->data;
  return true;
 }
 return false;
}

void QueueTraverse(LinkQueue Q, void (*fp)(ElemType))
{
 QueuePtr p = Q.front->next;
 while(p->next != NULL)
 {
  visit(p->data);
  p = p->next;
 }
}

void ClearQueue(LinkQueue *Q)
{
 ElemType x=0;
 while(Q->front != Q->rear)
 {
  DeQueue(Q,&x);
  Q->front = Q->front->next;
 }
}

bool EnQueue(LinkQueue *Q, ElemType e)
{
 QueuePtr p;
 p = (QueuePtr)malloc(sizeof(QNode));
 if(!p)
  return false;
 p->data = e;
 p->next = NULL;
 Q->rear->next = p;
 Q->rear = p;
 return true;
}

bool DeQueue(LinkQueue *Q, ElemType *e)
{
 QueuePtr p;
 if(Q->front == Q->rear)
  return false;
 p = Q->front->next;
 *e = p->data;
 Q->front->next = p->next;
 if(Q->rear == p)
  Q->rear = Q->front;
 free(p);
 return true;
}


Related articles: