Queue implementation in C Language

Source: Internet
Author: User

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);}}


 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.