Queue Data Structure - GeeksforGeeks (2024)

Last Updated : 11 May, 2024

Improve

A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of “First in, First out(FIFO), where the first element added to the queue is the first one to be removed. Queues are commonly used in various algorithms and applications for their simplicity and efficiency in managing data flow.

Queue Data Structure - GeeksforGeeks (1)

Queue Data Structure

Table of Content

  • What is Queue in Data Structures?
  • Basic Operations of Queue Data Structure
  • Applications of Queue
  • Basics of Queue Data Structure
  • Implementations of Queue in various Programming Languages
  • Other Implementations of Queue Data Structure
  • Easy Problems on Queue Data Structure
  • Medium Problems on Queue Data Structure
  • Hard Problems on Queue Data Structure

What is Queue in Data Structures?

A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. It operates like a line where elements are added at one end (rear) and removed from the other end (front).

Basic Operations of Queue Data Structure

  • Enqueue (Insert): Adds an element to the rear of the queue.
  • Dequeue (Delete): Removes and returns the element from the front of the queue.
  • Peek: Returns the element at the front of the queue without removing it.
  • Empty: Checks if the queue is empty.
  • Full: Checks if the queue is full.

Applications of Queue

  • Task scheduling in operating systems
  • Data transfer in network communication
  • Simulation of real-world systems (e.g., waiting lines)
  • Priority queues for event processing queues for event processing

Implementation of Queues

Queues can be implemented using Two techniques:

  • Implementations of Queue Data Structure using Arrays
  • Implementations of Queue Data Structure using Linked List

Basics of Queue Data Structure

  • Introduction to Queue – Data Structure and Algorithm Tutorials
  • Basic Operations of Queue Data Structure
  • Different Types of Queue
  • Applications, Advantages and Disadvantages of Queue

Implementations of Queue in various Programming Languages

  • Queue in C++ Standard Template Library (STL)
  • Queue Interface In Java
  • Queue In Python
  • Queue In C#
  • Queue in Javascript

Other Implementations of Queue Data Structure

  • Implementation of Deque using doubly linked list
  • Implement a stack using single queue
  • Implement Queue using Stacks
  • How to efficiently implement k Queues in a single array?
  • LRU Cache Implementation

Easy Problems on Queue Data Structure

  • Implement Stack using Queues
  • Detect cycle in an undirected graph using BFS
  • Breadth First Search or BFS for a Graph
  • Traversing directory in Java using BFS
  • Vertical order traversal of Binary Tree using Map
  • Print Right View of a Binary Tree
  • Find Minimum Depth of a Binary Tree
  • Check whether a given graph is Bipartite or not

Medium Problems on Queue Data Structure

  • Flatten a multilevel linked list
  • Level with maximum number of nodes
  • Find if there is a path between two vertices in a directed graph
  • Print all nodes between two given levels in Binary Tree
  • Find next right node of a given key
  • Minimum steps to reach target by a Knight
  • Islands in a graph using BFS
  • Level order traversal line by line | Set 3 (Using One Queue)
  • Find the first non-repeating character from a stream of characters

Hard Problems on Queue Data Structure

  • Sliding Window Maximum (Maximum of all subarrays of size K)
  • Flood Fill Algorithm
  • Minimum time required to rot all oranges
  • Shortest path in a Binary Maze
  • An Interesting Method to Generate Binary Numbers from 1 to n
  • Maximum cost path from source node to destination
  • Shortest distance between two cells in a matrix or grid
  • Snake and Ladder Problem
  • Find shortest safe route in a path with landmines
  • Count all possible walks from a source to a destination with exactly K edges
  • Minimum Cost of Simple Path between two nodes in a directed and weighted graph
  • Minimum Cost Path in a directed graph via given set of intermediate nodes
  • Find the first circular tour that visits all petrol pumps

Quick Links:

Recommended:

  • Learn Data Structure and Algorithms | DSA Tutorial
  • Queue in Go Language
  • Queue in Scala


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Queue Data Structure - GeeksforGeeks (2024)

FAQs

What is a queue in data structure? ›

A Queue is defined as a linear data structure that is open at both ends and the operations are performed in First In First Out (FIFO) order. We define a queue to be a list in which all additions to the list are made at one end, and all deletions from the list are made at the other end.

Is the queue FIFO or LIFO? ›

The primary difference between Stack and Queue Data Structures is that Stack follows LIFO while Queue follows FIFO data structure type.

What are the four types of queue? ›

There are four types of queues in a data structure: linear queue, circular queue, priority queue, and de-queue. Linear Queue inserts from one end while deletes from the other. In a circular queue, all nodes are circular.

What is an example of a queue? ›

The simplest example of a queue is the typical line that we all participate in from time to time. We wait in a line for a movie, we wait in the check-out line at a grocery store, and we wait in the cafeteria line (so that we can pop the tray stack).

What is the difference between a Stack and a queue? ›

A Stack is a linear data structure where removal and insertion occur at the same end. A Queue is also a linear data structure, but removal and insertion happen at different ends. A Stack follows the Last In, First Out (LIFO) principle, meaning the most recently inserted element is removed first.

What is the purpose of queue? ›

Queues are used to manage data flow and handle tasks in various applications, such as operating systems, network protocols, and data processing systems. They are also used to implement algorithms like breadth-first search, which involves exploring nodes in a graph level-by-level.

Why choose FIFO over LIFO? ›

In terms of investing in accounting inventory, FIFO is usually a better method for inventory when prices are rising, and LIFO accounting is better when prices fall because more expensive products are sold first.

Do restaurants use FIFO or LIFO? ›

First-In, First-Out (FIFO)

First-in, first-out inventory measurement is the most common inventory costing technique as it's easy, reliable and accurate. FIFO assumes that goods purchased first, are sold first – usual practice in restaurants as chefs tend to use the ingredients that are closest to expiration first.

Why stack is LIFO? ›

Since the element at the top of the stack is the most recently inserted element using the insert operation, and it is also the one to be removed first by the delete operation, the stack is called a Last In First Out (LIFO) list.

What are the 3 primary methods for a queue? ›

The queue data structure has three main methods:
  • enqueue (adds a node to the back of the queue)
  • dequeue (removes node at the front of the queue)
  • peek (returns value of node at the front of the queue, without removing it)

Which type of queue is best? ›

A circular queue permits better memory utilization than a simple queue when the queue has a fixed size. In this queue, the last node points to the first node and creates a circular connection. Thus, it allows us to insert an item at the first node of the queue when the last node is full and the first node is free.

What are the disadvantages of queue in data structure? ›

These limitations of queues include the lack of random access to elements, limited capacity, and memory overhead. Despite these drawbacks, queues remain a useful tool in managing data and are widely used in a variety of applications.

What is a real life example of stack queue? ›

A real-life example of a stack can be the Undo/Redo operation in Word or Excel. A real-life example of a queue can be an operating system process scheduling queues.

Where is queue mostly used? ›

Queues are typically used to manage threads in multithreading and implementing priority queuing systems. In this article, we will learn about different types of queue data structures, basic operations performed on them, implementation, and queue applications. A queue is an important data structure in programming.

When to use queue data structure? ›

Application of Queue in Operating System
  1. They can be used for algorithms like First Come First Serve(FCFS).
  2. It is used as a buffer for input devices like the Keyboard.
  3. It is also used for CPU Scheduling.
  4. It is widely used for spooling in Printers.
  5. Queues are also used in Memory Management.
Jun 28, 2022

What is a data queue? ›

A Data queue is a system object that exists on IBM® i system. Data queues are a cross-reference between data areas and message queues. These data queues help you to communicate asynchronously between programs, also known as control language programs.

What is a simple queue? ›

Simple Queue

A simple queue is the most basic queue. In this queue, the enqueue operation takes place at the rear, while the dequeue operation takes place at the front: Its applications are process scheduling, disk scheduling, memory management, IO buffer, pipes, call center phone systems, and interrupt handling.

What do you mean by queue? ›

: a waiting line especially of persons or vehicles. 3. a. : a sequence of messages or jobs held in temporary storage awaiting transmission or processing.

What is queue and why is it known as FIFO? ›

A FIFO queue is a queue that operates on a first-in, first-out (FIFO) principle. First-in, first-out means that the request (like a customer in a store or a print job sent to a printer) is processed in the order in which it arrives.

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5666

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.