Queue Data Structure - GeeksforGeeks (2024)

Last Updated : 30 Jul, 2024

Comments

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 (2)

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 - ") } document.getElementById('article-video-tab-content').style.display = 'block'; } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); // error handling for no compatible source player.on('error', function() { var error = player.error(); console.log("Video Error: ", error); if (error && error.code === 4) { console.log("No compatible source was found for this media."); hideVideoPlayer(); } }); }, function(err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); hideVideoPlayer(); // hiding video in case of timeout (requirejs) console.log(err); }); // function to hide the video player function hideVideoPlayer() { var videoPlayer = document.getElementById('article-video'); if (videoPlayer) { videoPlayer.parentNode.removeChild(videoPlayer); } } /*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 queue in data structure geeksforgeeks? ›

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.

How to solve problems involving queues? ›

Updated: 10 Common Queue Problems and Solutions Your Customers Will Love
  1. Idea #1: Magnetic Base Stanchions. ...
  2. Idea #2: Publish Estimated Wait Times. ...
  3. Idea #3: Start the Process Sooner. ...
  4. Idea #4: Add Impulse Merchandising to Your Checkout. ...
  5. Idea #5: Use Extra-Long Retractable Belt Barriers.
Dec 21, 2023

What is queue and its types in data structure? ›

The queue data structure is a linear data structure used to hold items. In programming, a queue is an important data structure. Elements in this data structure are stored using the FIFO approach. There are four types of queues in a data structure: linear queue, circular queue, priority queue, and de-queue.

How are queues represented in memory? ›

One simpler way to represent it is by using a double linked list. Another popular representation is using a circular array (as used in a circular queue). The following four operations are possible on a deque which consists of a list of items: 1. Push_DQ(ITEM): To insert ITEM at the FRONT end of a deque.

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 drawbacks of queue in data structure? ›

Disadvantages of Queue

Inserting and removing elements from the middle is complex. Queues are not readily searchable. This is because it takes O(N) time to search.

What is a real life example of queue in data structure? ›

Real-Life Queue in Data Structure Example

A line of people is waiting to buy a ticket at a cinema hall. A new person will join the line from the end, and the person standing at the front will be the first to get the ticket and leave the line.

Can a queue be an array? ›

You can represent queues in the form of an array using pointers: front and rear. For example, the array shown in the diagram below consists of 11 characters having S at the front and N at the rear node.

What are queues good for? ›

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.

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 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 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 an example of a queue? ›

The ticket queue outside a cinema hall is a real-world example of a queue, where the person who enters first gets the ticket first, and the person who enters last gets the ticket last.

What is queue and deque in data structure? ›

Double Ended or Deque Queue is an extended version of the Queue data structure that supports insert and delete operations at both ends. Deque is the short term for "Double-Ended Queue". To use Deque in C++ Standard Template Library, we can use #include<deque> header.

References

Top Articles
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 6072

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.