Queue implementation in C Language
A queue is different from a stack. It is an FIFO queue, that is, an FIFO queue is required for element extraction in a FIFO queue. Queues can be implemented using arrays or linked lists, which is simple but useful in some cases. To achieve this, you only need to maintain the first and last pointer of the team. Below is the list queue I implemented.
Queue. h
#ifndef __QUEUE_H#define __QUEUE_H#include
#include
struct QueueNode;struct queue;typedef Vertex ElementType;typedef struct QueueNode *Node;typedef struct queue *Queue;struct QueueNode{ElementType element;Node next;};struct queue{Node first;Node last;};Queue createQueue();int isEmpty(Queue Q);void EnQueue(ElementType X,Queue Q);ElementType DeQueue(Queue Q);void deleteQueue(Queue Q);#endif
Queue. c
#include queue.hQueue createQueue(){Queue Q;Node node;node=(Node)malloc(sizeof(struct QueueNode));if(node==NULL){printf(out of space);exit(-1);}node->next=NULL;Q=(Queue)malloc(sizeof(struct queue));if(Q==NULL){printf(out of space);exit(-1);}Q->first=node;Q->last=node;return Q;}int isEmpty(Queue Q){if(Q->first==Q->last)return 1;elsereturn 0;}void EnQueue(ElementType X,Queue Q){Node node;node=(Node)malloc(sizeof(struct QueueNode));if(node==NULL){printf(out of space);exit(-1);}node->element=X;node->next=NULL;Q->last->next=node;Q->last=node;}ElementType DeQueue(Queue Q){ElementType x;Node p;if(isEmpty(Q)){printf(queue is empty);exit(-1);}p=Q->first->next;Q->first->next=p->next;x=p->element;if(p==Q->last){Q->last=Q->first;}free(p);return x;}void deleteQueue(Queue Q){while(!isEmpty(Q)){DeQueue(Q);}}