Implement Stack Using Queue | Programming and Data Structures - Computer Science Engineering (CSE) PDF Download

Introduction

Given a Queue data structure that supports standard operations like enqueue() and dequeue(). The task is to implement a Stack data structure using only instances of Queue and Queue operations allowed on the instances.

Implement Stack Using Queue | Programming and Data Structures - Computer Science Engineering (CSE)

 Stack can be implemented using two queues. Let Stack to be implemented be ‘s’ and queues used to implement are ‘q1’ and ‘q2’. Stack ‘s’ can be implemented in two ways:

Implement Stack using Queues By making push() operation costly:

Below is the idea to solve the problem:

The idea is to keep newly entered element at the front of ‘q1’ so that pop operation dequeues from ‘q1’. ‘q2’ is used to put every new element in front of ‘q1’.

  • Follow the below steps to implement the push(s, x) operation: 
    • Enqueue x to q2.
    • One by one dequeue everything from q1 and enqueue to q2.
    • Swap the queues of q1 and q2.
  • Follow the below steps to implement the pop(s) operation: 
    • Dequeue an item from q1 and return it.

Below is the implementation of the above approach.
C++

/* Program to implement a stack using

two queue */

#include <bits/stdc++.h>

using namespace std;

class Stack {

    // Two inbuilt queues

    queue<int> q1, q2;

public:

    void push(int x)

    {

        // Push x first in empty q2

        q2.push(x);

        // Push all the remaining

        // elements in q1 to q2.

        while (!q1.empty()) {

            q2.push(q1.front());

            q1.pop();

        }

        // swap the names of two queues

        queue<int> q = q1;

        q1 = q2;

        q2 = q;

    }

    void pop()

    {

        // if no elements are there in q1

        if (q1.empty())

            return;

        q1.pop();

    }

    int top()

    {

        if (q1.empty())

            return -1;

        return q1.front();

    }

    int size() { return q1.size(); }

};

// Driver code

int main()

{

    Stack s;

    s.push(1);

    s.push(2);

    s.push(3);

    cout << "current size: " << s.size() << endl;

    cout << s.top() << endl;

    s.pop();

    cout << s.top() << endl;

    s.pop();

    cout << s.top() << endl;

    cout << "current size: " << s.size() << endl;

    return 0;

}

Output

current size: 3

3

2

1

current size: 1

Time Complexity

  • Push operation: O(N), As all the elements need to be popped out from the Queue (q1) and push them back to Queue (q2).
  • Pop operation: O(1), As we need to remove the front element from the Queue.

Auxiliary Space: O(N), As we use two queues for the implementation of a Stack.

Implement Stack using Queues by making pop() operation costly:

Below is the idea to solve the problem:

The new element is always enqueued to q1. In pop() operation, if q2 is empty then all the elements except the last, are moved to q2. Finally, the last element is dequeued from q1 and returned.

  • Follow the below steps to implement the push(s, x) operation: 
    • Enqueue x to q1 (assuming the size of q1 is unlimited).
  • Follow the below steps to implement the pop(s) operation: 
    • One by one dequeue everything except the last element from q1 and enqueue to q2.
    • Dequeue the last item of q1, the dequeued item is the result, store it.
    • Swap the names of q1 and q2
    • Return the item stored in step 2.

Below is the implementation of the above approach:

C++

// Program to implement a stack

// using two queue

#include <bits/stdc++.h>

using namespace std;

class Stack {

    queue<int> q1, q2;

public:

    void pop()

    {

        if (q1.empty())

            return;

        // Leave one element in q1 and

        // push others in q2.

        while (q1.size() != 1) {

            q2.push(q1.front());

            q1.pop();

        }

        // Pop the only left element

        // from q1

        q1.pop();

        // swap the names of two queues

        queue<int> q = q1;

        q1 = q2;

        q2 = q;

    }

    void push(int x) { q1.push(x); }

    int top()

    {

        if (q1.empty())

            return -1;

        while (q1.size() != 1) {

            q2.push(q1.front());

            q1.pop();

        }

        // last pushed element

        int temp = q1.front();

        // to empty the auxiliary queue after

        // last operation

        q1.pop();

        // push last element to q2

        q2.push(temp);

        // swap the two queues names

        queue<int> q = q1;

        q1 = q2;

        q2 = q;

        return temp;

    }

    int size() { return q1.size(); }

};

// Driver code

int main()

{

    Stack s;

    s.push(1);

    s.push(2);

    s.push(3);

    cout << "current size: " << s.size() << endl;

    cout << s.top() << endl;

    s.pop();

    cout << s.top() << endl;

    s.pop();

    cout << s.top() << endl;

    cout << "current size: " << s.size() << endl;

    return 0;

Output

current size: 3

3

2

1

current size: 1

Time Complexity

  • Push operation: O(1), As, on each push operation the new element is added at the end of the Queue.
  • Pop operation: O(N), As, on each pop operation, all the elements are popped out from the Queue (q1) except the last element and pushed into the Queue (q2).

Auxiliary Space: O(N) since 2 queues are used.

Implement Stack using 1 queue

Below is the idea to solve the problem:

Using only one queue and make the queue act as a Stack in modified way of the above discussed approach.

Follow the below steps to implement the idea

  • The idea behind this approach is to make one queue and push the first element in it. 
  • After the first element, we push the next element and then push the first element again and finally pop the first element. 
  • So, according to the FIFO rule of the queue, the second element that was inserted will be at the front and then the first element as it was pushed again later and its first copy was popped out. 
  • So, this acts as a Stack and we do this at every step i.e. from the initial element to the second last element, and the last element will be the one which we are inserting and since we will be pushing the initial elements after pushing the last element, our last element becomes the first element.

Below is the implementation for the above approach
C++

#include <bits/stdc++.h>

using namespace std;

// Stack Class that acts as a queue

class Stack {

    queue<int> q;

public:

    void push(int data);

    void pop();

    int top();

    int size();

    bool empty();

};

// Push operation

void Stack::push(int data)

{

    // Get previous size of queue

    int s = q.size();

    // Push the current element

    q.push(data);

    // Pop all the previous elements and put them after

    // current element

    for (int i = 0; i < s; i++) {

        // Add the front element again

        q.push(q.front());

        // Delete front element

        q.pop();

    }

}

// Removes the top element

void Stack::pop()

{

    if (q.empty())

        cout << "No elements\n";

    else

        q.pop();

}

// Returns top of stack

int Stack::top() { return (q.empty()) ? -1 : q.front(); }

// Returns true if Stack is empty else false

bool Stack::empty() { return (q.empty()); }

int Stack::size() { return q.size(); }

int main()

{

    Stack st;

    st.push(1);

    st.push(2);

    st.push(3);

    cout << "current size: " << st.size() << "\n";

    cout << st.top() << "\n";

    st.pop();

    cout << st.top() << "\n";

    st.pop();

    cout << st.top() << "\n";

    cout << "current size: " << st.size();

    return 0;

}

Output

current size: 3

3

2

1

current size: 1

Time Complexity

  • Push operation: O(N)
  • Pop operation: O(1)

Auxiliary Space: O(N) since 1 queue is used.

The document Implement Stack Using Queue | Programming and Data Structures - Computer Science Engineering (CSE) is a part of the Computer Science Engineering (CSE) Course Programming and Data Structures.
All you need of Computer Science Engineering (CSE) at this link: Computer Science Engineering (CSE)
119 docs|30 tests

Top Courses for Computer Science Engineering (CSE)

119 docs|30 tests
Download as PDF
Explore Courses for Computer Science Engineering (CSE) exam

Top Courses for Computer Science Engineering (CSE)

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Important questions

,

practice quizzes

,

Implement Stack Using Queue | Programming and Data Structures - Computer Science Engineering (CSE)

,

Viva Questions

,

MCQs

,

shortcuts and tricks

,

past year papers

,

Summary

,

Exam

,

Extra Questions

,

Implement Stack Using Queue | Programming and Data Structures - Computer Science Engineering (CSE)

,

Sample Paper

,

video lectures

,

pdf

,

Free

,

Implement Stack Using Queue | Programming and Data Structures - Computer Science Engineering (CSE)

,

Previous Year Questions with Solutions

,

ppt

,

Semester Notes

,

mock tests for examination

,

study material

,

Objective type Questions

;