Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (
add
, top
, pop
, and empty
).Example:
isEmpty(): false: Top() : 1: Size() : 1
isEmpty(): false: Pop() : 2: Size() : 1
Top(): 1: isEmpty(): false: Pop() : 1: Size() : 0
Approach
Java
import java.util.ArrayDeque;import java.util.Queue;public class ImplStackUsingQueues {public static void main(String[] args) {// create stack with sizeStackQueue<Integer> s = new StackQueue<>();// add 1 elements.push(1);System.out.println("isEmpty(): " + s.isEmpty() +": Top() : " + s.top() + ": Size() : " + s.size());// pop elements.push(2);System.out.println("isEmpty(): " + s.isEmpty() +": Pop() : " + s.pop() + ": Size() : " + s.size());// pop elementSystem.out.println("Top(): " + s.top() + ": isEmpty(): "+ s.isEmpty() + ": Pop() : " + s.pop()+ ": Size() : " + s.size());}}class StackQueue<T> {Queue<T> q1, q2;public StackQueue() {q1 = new ArrayDeque<>();q2 = new ArrayDeque<>();}public int size() {return q1.size();}// Remove the top item from the stackpublic T pop() {if (q1.isEmpty()) {System.out.println("Underflow!!");System.exit(0);}return q1.poll();}public T top() {if (q1.isEmpty()) {System.out.println("Underflow!!");System.exit(0);}return q1.peek();}public boolean isEmpty() {return q1.isEmpty();}// insert item on to the stackvoid push(T val) {// move all the item from q1 to q2while (!q1.isEmpty()) {q2.add(q1.peek());q1.poll();}q1.add(val);// move all the item back from q2 to q1while (!q2.isEmpty()) {q1.add(q2.peek());q2.poll();}}}
C++
#include <bits/stdc++.h>using namespace std;class StackQueue{public:queue<int> q1, q2;StackQueue() {}int size() {return q1.size();}// Remove the top item from the stackint pop() {if (q1.empty()) {cout<<"Underflow!!";return -1;}else{int temp=q1.front();q1.pop();return temp;}}int top() {if (q1.empty()) {cout<<"Underflow!!";return -1;}return q1.front();}bool isEmpty() {return q1.empty();}// insert item on to the stackvoid push(int val){// move all the item from q1 to q2while (!q1.empty()) {q2.push(q1.front());q1.pop();}q1.push(val);// move all the item back from q2 to q1while (!q2.empty()) {q1.push(q2.front());q2.pop();}}};int main(){// create stack with sizeStackQueue s;// add 1 elements.push(1);cout<<"isEmpty(): "<<s.isEmpty();cout<<": Top() : "<<s.top()<<": Size() : "<<s.size()<<"\n";// pop elements.push(2);cout<<"isEmpty(): "<<s.isEmpty();cout<<": Pop() : "<<s.pop();cout<<": Size() : "<<s.size()<<"\n";// pop elementcout<<"Top(): "<<s.top();cout<<": isEmpty(): "<<s.isEmpty();cout<<": Pop() : "<<s.pop();cout<<": Size() : "<<s.size()<<"\n";return 0;}
No comments:
Post a Comment