The C language implements the chain queue code

  • 2020-06-07 04:56:21
  • OfStack

This paper shares the specific code of C language chain queue for your reference, the specific content is as follows


#include <stdio.h>

/*  The structure of a queue  */
typedef int DataType;
#define NODE_LEN sizeof(NODE) 

/*  Queue node  */
typedef struct stNode
{
  DataType data;
  struct stNode* next;
}NODE;

/*  The queue  */
typedef struct stQueue
{
  NODE* head; // The head of the queue 
  NODE* tail; // Queue tail 
}QUEUE;

/*  Initialize queue , Unheaded node */
int initQueue(QUEUE* INQueue)
{

  INQueue->head = NULL;
  INQueue->tail = NULL;

  return 0;
}

/*  Insert from the end of the line 1 An element  */
int enQueue(QUEUE* InQueue,DataType InData)
{
  NODE* pNewNode = (NODE*)malloc(NODE_LEN);
  if (pNewNode == NULL)
  {
    return -1;
  }

  pNewNode->data = InData;
  pNewNode->next = NULL;

  /*  Determine if there are nodes in the queue  */
  if (InQueue->head == NULL)
  {
    InQueue->head = pNewNode;
    InQueue->tail = pNewNode;
  }
  else
  {
    InQueue->tail->next = pNewNode;
    InQueue->tail = pNewNode;
  }

  return 0;
}

/*  Traverse the queue  */
int visitQueue(QUEUE InQueue)
{
  QUEUE* pstTemp = &InQueue;

  /*  Determine if the queue is empty  */
  if (pstTemp->head == NULL)
  {
    printf("visitQueue: this queue is empty\n");
    return -1;
  }

  /*  Iterate over all the elements in the queue  */
  while (pstTemp->head->next != NULL)
  {
    printf("%d ", pstTemp->head->data);
    pstTemp->head = pstTemp->head->next;
  }
  printf("%d \n", pstTemp->head->data);

  return 0;
}

/*  Out of the queue  */
int delQueue(QUEUE* InQueue,DataType* OutData)
{
  if (InQueue->head == NULL)
  {
    printf("delQueue: this queue is empty\n");
    return -1;
  }

  *OutData = InQueue->head->data;

  NODE* pstTemp = InQueue->head;
  InQueue->head = InQueue->head->next;

  delete pstTemp;
  return 0;
}

/*  Determine if the queue is empty  */
int isEmptyQueue(QUEUE InQueue)
{
  if (InQueue.head == NULL)
  {
    return 0; // Is an empty queue 
  }
  return 1; // Not an empty queue 
}

int main()
{
  /*  create 1 A queue  */
  QUEUE queue;
  DataType data;

  initQueue(&queue);

  /*  In the queue  */
  enQueue(&queue, 12);
  enQueue(&queue, 11);
  enQueue(&queue, 2);
  visitQueue(queue);

  /*  Out of the queue  */
  delQueue(&queue, &data);
  visitQueue(queue);
  printf("data = %d\n", data);

  visitQueue(queue);

  if (0 == isEmptyQueue(queue))
  {
    printf("This is empty queue\n");
  }
  else
  {
    printf("This is not empty queue\n");
  }
  return 0;
}

Related articles: