A queue is an ordered collection of items in which items may be inserted at one end known as rear end and items may be inserted at one end known as front end. A queue is also known as FIFO (first in first out) structure because the element which is inserted first will be the first element to be deleted. Diagrammatically it is shown as,
About Linked list
A linked list is a way to store a collection of elements. Like an array, these can be character or integers. Each element in a linked list is stored in the form of a node.
Declaring a Queue
In C language, a stack list can be implemented using structure and pointers, it’s simpler to single linked list.
struct queue { int data; struct queue*next; }; typedef struct queue QUEUE; QUEUE*front=NULL; QUEUE*rear=NULL;
Queue Insert Operation
QInsert, It’s a simple process to insert or add a new element to queue to the rear end using linked list add node approach.
void qinsert() { QUEUE*temp; if(rear==NULL) { rear=(QUEUE*)malloc(sizeof(QUEUE)); printf("\nEnter data: "); scanf("%d",&rear->data); rear->next=NULL; front=rear; return; } else { temp=(QUEUE*)malloc(sizeof(QUEUE)); printf("\nEnter Data: "); scanf("%d",&temp->data); temp->next=NULL; rear->next=temp; rear=temp; return; } }
Queue Delete Operation
QDelete, It’s a simple process to delete or remove an element from queue from front end using linked list delete node approach.
void qdelete() { QUEUE*temp; if(front==NULL) { printf("\nQUEUE IS UNDERFLOW(EMPTY):"); return; } else { temp=front; front=front->next; temp->next=NULL; printf("\ndeleted data:%d",temp->data); free(temp); temp=NULL; if(front==NULL) //last element only rear=NULL; return; } }
Queue Display Operation
QDisplay, It’s a simple process to display or traversal operation on Queue without deleting an element
void qdisplay() { QUEUE*temp; if(front==NULL) { printf("\nQUEUE IS EMPTY: "); return; } else { printf("\nQUEUE DATA: "); temp=front; do { printf("%d ",temp->data); temp=temp->next; }while(temp!=NULL); } }
main() function Implementation
int main() { int option; while(1) { clrscr(); printf("\n1.FOR INSERT :"); printf("\n2.FOR DELETE :"); printf("\n3.FOR DISPLAY: "); printf("\n4.FOR EXIT...:"); scanf("%d",&option); switch(option) { case 1: qinsert(); break; case 2: qdelete(); getch(); break; case 3: qdisplay(); getch(); break; case 4: return 0; default: printf("\ninvalid option: "); } } }