The C language implements chain queues

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

Record 1 C language to achieve the chain queue code, for your reference, the specific content is as follows

typedef int ElemType;

// Node definition of the chain queue  
typedef struct node{
  ElemType val;
  struct node* next;

// The definition of a chain queue, including the head pointer and the tail pointer  
typedef struct queue {
  QueueNode* front;
  QueueNode* rear;

// Initialize queue  
LinkedQueue* initQueue() {
  LinkedQueue* queue = (LinkedQueue*)malloc(sizeof(LinkedQueue));
  queue->front = (QueueNode*)malloc(sizeof(QueueNode));
  queue->front->next = NULL;
  queue->rear = queue->front;

// Elements of the team  
void enQueue(LinkedQueue* queue, ElemType elem) {
  QueueNode* node = (QueueNode*)malloc(sizeof(QueueNode));
  node->val = elem;
  node->next = NULL;
  queue->rear->next = node;
  queue->rear = node;

// Whether the queue is empty  
bool isQueueEmpty(LinkedQueue* queue) {
  return queue->front == queue->rear; 

// Elements of the team  
ElemType deQueue(LinkedQueue* queue) {
  if(!isQueueEmpty(queue)) {
    QueueNode* p = queue->front;
    queue->front = p->next;
    ElemType e = queue->front->val;
    return e;
  return NULL;

int main()
  LinkedQueue* queue = initQueue();
  int i;
  for(i = 0; i < 20; i++) {
    enQueue(queue, i);
  while(!isQueueEmpty(queue)) {
    printf("deQueue: %d\n", deQueue(queue));
  return 0;

It should be noted that:

When initializing the queue, both the header and the tail point to the same node (the header does not store data); Judge whether the queue is empty, that is, judge whether the head pointer and the tail pointer are the same; The header element is the value in the next node of the current front pointer

Related articles: