Coders Packet

Queue Implementation In C++ Using Stack

By Ashwini Laxman Jadhav

In this tutorial, you learn how to implement a queue using a stack and what is the logic behind it in C++. There is some methods pop(), push(), top() & size() which you can implement in this tutorial.

So, before implementing the whole program you need to know what is the basic difference between queue and stack, then only you will able to implement its logic. Stack is a data structure that works on the last in first out method (LIFO) and it involves a method called push() for insertion of values, pop() for removing values from the stack, and top() which returns your top most value present in your stack.

The queue is a data structure that works on the first in first out method (FIFO) and it involves en queue() for inserting values, de queue() for removing values, and peek() which gives you the value at front of the queue.

Implementation Of Queue In C++ Using Stack

Here is some part of the program if you want the whole source code then download it from the below file section.

Enlightener#include<bits/stdc++.h>
using namespace std;

class Queue
{
  stackin;
  stackout;
  
  public:
    int N;
    
    Queue()
    {
      N=0;
    }
    

The logic for implementing the above program:-

1] first you need to take two containers (STACK), the first is for input purposes and another is for output purposes.

LIFO                                                FIFO

 [4                                                     [1

 3     output of this is (4 3 2 1)  -----      2 output of this is (1 2 3 4)

 2                                                        3

 1]                                                      4]

(stack method)                          (queue method)

 

consider, that the above-given values with brackets are two stacks. So for implementing queue, you need the values in your output i.e:- 1 2 3 4 but in the stack, the values are returned in this form i.e:- 4 3 2 1.

For converting this 4 3 2 1 to 1 2 3 4 you need to use two stacks one for storing values and then when we pop() element from one stack we need to push these values to another stack i.e:- output stack. Once you are done with popping the element from the input stack and pushing it to the output stack, You need to pop the element from the output stack and that is your output.

For understanding the whole logic you need to just understand the LIFO technique of stack.

Download Complete Code

Comments

No comments yet