etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Queue using linked list c++

In this post, you will learn how to implement a Queue using C++ programming language.

A queue is a linear data structure where insertion of element is done from one end and deletion from the other end. The queue is like a line of person at polling booth where the first person in the line is first voted. This is called First-In-First-Out (FIFO). Insertion of the element is done from the one end called FRONT end and deletion is done from the other end called REAR.

Queue Implementation



Queue Operations

These are the operations performed by a queue.

  • Enqueue - The element to add in a queue. If the queue is full, then it is said to be an overflow condition.
  • Dequeue - The element to delete in a queue. If the queue is empty, then it is said to be an underflow condition.
  • Peek - Retrieve the element from the front end of the queue without removing it from the queue.
  • IsEmpty - Check if the queue is empty or not.
  • Size - Return the total number of elements present in the queue.
  • Front - Get the front item from queue.
  • Rear - Get the last item from queue.




Algorithm to Insert Element in a Queue

Step 1: IF REAR = MAX-1
	print('Queue Overflow')
	return
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = NUM
Step 4: EXIT

In the above algorithm, we have checked the existence of space in the queue. If there is no space then print 'Queue Overflow' and the code is exited and if not then, we check the element at the FRONT and REAR, if both are empty then set both to 0 else increase REAR with one and insert element from the REAR end and return.





Algorithm to Delete Element in a Queue

Step 1: IF FRONT = -1 OR FRONT > REAR
	print('Queue Underflow')
	return
ELSE
SET FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT

In the above algorithm, we have checked the existence of elements in the queue. If there is no any element, then print 'Queue Underflow' and the code is exited and if not, then FRONT is increased by one and point to the next element in the queue.





Queue Implementation using linked list in C++

The linked list is a non primitive data structure which is free from fixed memory size restriction. It is static free and user can add any number of elements when required. We can use this to create other data structures, like stacks, queues, etc. It allows the insertion and deletion of nodes at any point in the list.

The function enqueue() inserts an element into the queue. Initially it checks, if rear is NULL, then the queue is empty and a single element is inserted. Otherwise, a node is inserted after rear with the required element and then that node is set to rear.

In the function dequeue(), firstly check if the queue is empty. If it is, then print the result as "Queue Underflow". If there is only one element in the queue that is deleted and front and rear are set to NULL. Otherwise, the element at front is deleted and front points to the next element.

In the function show(), if front and rear are NULL then queue is empty. Otherwise, using while loop print all the queue elements starting from front to rear with the help of temp variable.

#include <iostream>
using namespace std;
struct node {
   int data;
   struct node *next;
};
struct node* front = NULL;
struct node* rear = NULL;
struct node* temp;

void enqueue() {
   int val;
   cout<<"Enter value to inset in queue : ";
   cin>>val;
   if (rear == NULL) {
      rear = (struct node *)malloc(sizeof(struct node));
      rear->next = NULL;
      rear->data = val;
      front = rear;
   } else {
      temp=(struct node *)malloc(sizeof(struct node));
      rear->next = temp;
      temp->data = val;
      temp->next = NULL;
      rear = temp;
   }
}
void dequeue() {
   temp = front;
   if (front == NULL) {
      cout<<"QUEUE UNDERFLOW!"<<endl;
      return;
   }
   else
   if (temp->next != NULL) {
      temp = temp->next;
      cout<<"Element deleted from queue : "<<front->data<<endl;
      free(front);
      front = temp;
   } else {
      cout<<"Element deleted from queue : "<<front->data<<endl;
      free(front);
      front = NULL;
      rear = NULL;
   }
}
void show() {
   temp = front;
   if ((front == NULL) && (rear == NULL)) {
      cout<<"QUEUE UNDERFLOW!"<<endl;
      return;
   }
   while (temp != NULL) {
      cout<<temp->data<<" ";
      temp = temp->next;
   }
   cout<<endl;
}
int main() {
   int choice;
   cout<<"1) Insert element to queue"<<endl;
   cout<<"2) Delete element from queue"<<endl;
   cout<<"3) Display all the elements of queue"<<endl;
   cout<<"4) Exit"<<endl;
   do {
      cout<<"Enter your choice : ";
      cin<<choice;
      switch (choice) {
         case 1: enqueue();
         break;
         case 2: dequeue();
         break;
         case 3: show();
         break;
         case 4: cout<<"Exit"<<endl;
         break;
         default: cout<<"Invalid choice"<<endl;
      }
   } while(choice!=4);
   return 0;
}
Output of the above code:
1) Insert element to queue
2) Delete element from queue
3) Display all the elements of queue
4) Exit
Enter your choice : 1
Enter value to inset in queue : 39
Enter your choice : 1
Enter value to inset in queue : 90
Enter your choice : 3
39 90 
Enter your choice : 2
Element deleted from queue : 39
Enter your choice : 3
90 
Enter your choice : 




Related Articles

Implementation of queue using array in C
Queue implementation in Python
Queue Implementation in C
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Prime factors of a number in c
Armstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to convert Decimal to Octal
C program to convert decimal to binary
C program to check whether a number is even or odd




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple pagination in PHP with MySQL
-----------------
How to generate QR Code in PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
PHP MYSQL Advanced Search Feature
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
jQuery File upload progress bar with file size validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
To check whether a year is a leap year or not in php
-----------------
Php file based authentication
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
PHP Secure User Registration with Login/logout
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to print specific part of a web page in javascript
-----------------
Detect Mobile Devices in PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Google Street View API Example
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
PHP Programming Error Types
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
PHP Getting Document of Remote Address
-----------------
How to display PDF file in web page from Database in PHP
-----------------
File Upload Validation in PHP
-----------------
PHP FTP Connection and File Handling
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.