6) 5) Implement Stack using Two Queues which is pop() efficient
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package question6;
import [Link];
import [Link];
/**
*
* @author Nischal
*/
public class Question6 {
// Two inbuilt queues
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
// To maintain current number of
// elements
int curr_size;
Question6()
{
curr_size = 0;
}
void push(int x)
{
curr_size++;
// Push x first in empty q2
[Link](x);
// Push all the remaining
// elements in q1 to q2.
while (![Link]()) {
[Link]([Link]());
[Link]();
}
// swap the names of two queues
Queue<Integer> q = q1;
q1 = q2;
q2 = q;
}
void pop()
{
// if no elements are there in q1
if ([Link]())
return;
[Link]();
curr_size--;
}
int top()
{
if ([Link]())
return -1;
return [Link]();
}
int size()
{
return curr_size;
}
// driver code
public static void main(String[] args)
{
Question6 s = new Question6();
[Link](1);
[Link](2);
[Link](3);
[Link]("current size: " + [Link]());
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]("current size: " + [Link]());
}
}