Queue using Linked List
A Queue is a data structure that stores the data elements in a sequential manner. It is also called FIFO( First In First Out) or LILO(Last In Last Out). In the queue, insertion happens at the end(rear) and deletion from the front. To better understand we can consider a queue at the reservation counter of a movie theatre. Here the person standing in the front will book the ticket first and then the next person and so on.
Queue ADT
Enqueue(int data): Insert an element at the end of the queue
int Dequeue(): Removes and returns the element at the front of the queue
Auxiliary Queue Operations
Front(): Prints the element at the front of the queue
int QueueSize(): Returns the count of element in the queue
int isEmpty(): Check whether the queue is empty or not
//C code to implement Queue using linked List #include<stdio.h> #include<stdlib.h> typedef struct node{ int data; struct node *next; }QUEUE; QUEUE *front = NULL; QUEUE *rear = NULL; void printQueue() { QUEUE *temp = front; if( temp == NULL ) { printf("\nQueue is empty!"); return; } while( temp != NULL ) { printf("%d\t",temp->data); temp = temp->next; } } QUEUE *newNodeF( int data ) { QUEUE* newNode = (QUEUE*)malloc(sizeof(QUEUE)); newNode->data = data; newNode->next = NULL; return newNode; } void enQueue() { int i,n,data; QUEUE *newNode,*ptr; printf("\nEnter number of elements:"); scanf("%d",&n); for( i = 0; i < n; i++ ) { printf("\nEnter element to enqueue:"); scanf("%d",&data); newNode=newNodeF(data); if( front == NULL ) { front = rear = newNode; } else { rear->next = newNode; rear = newNode; } } } int deQueue() { if( front == NULL ) { printf("\nQueue is empty!"); return 0; } QUEUE *temp = front; front = front->next; int data = temp->data; free(temp); return data; } int main() { enQueue(); printf("\nQueue is\t"); printQueue(); int data = deQueue(); if( data != 0 ) { printf("\nDequeue element is %d",data); } printf("\nQueue is\t"); printQueue(); return 0; }
$gcc queue.c $ ./a.out Enter number of elements:5 Enter element to enqueue:1 Enter element to enqueue:2 Enter element to enqueue:3 Enter element to enqueue:4 Enter element to enqueue:5 Queue is 1 2 3 4 5 Dequeue element is 1 Queue is 2 3 4 5 $ |
also see
C Programming language |
Go Programming language |
Linked List | Array |
Stack | Queue |
Puzzle | Reasoning |
Aptitude | HTML |